前端数据大部分都来源于后端,我们在页面刚渲染的时候发起异步请求,然后在返回结果中进行setState({})就有可能会引起这个报错。
即
Warning:setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component.This is a no-op. Please check the code for the xxx component.
这是因为组件还没有被加载完成就执行setState({}) 这个时候我们就要在生命周期里进行操作
即
componentWillMount(){
this.setState({
mounted:true ///// mounted 是自定义属性主要为了在setState({})时加个判断
})
}
componentWillUnmount() {
this.setState({
mounted:true
})
}
之后在异步请求返回结果后setState的时候进行判断
即
if(this.state.mounted){
this.setState({
.....
});
}