当前位置: 代码迷 >> 综合 >> setState(...): Can only update a mounted or mounting component. This usually means you called setSta
  详细解决方案

setState(...): Can only update a mounted or mounting component. This usually means you called setSta

热度:72   发布时间:2023-12-26 02:29:06.0

转载:https://blog.csdn.net/qq_32234865/article/details/79860026

错误

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component.
  • 1

原因

在componentWillMount方法里调用异步方法,比如发请求,然后在异步回调里SetState,有可能界面切出去了,回调才回来SetState,这时候页面已经被卸载(unmounted)了,就会报上面的错。

解决

 // 1.在构造函数里定义一个未卸载标志位:constructor(props) {this.state={isMounted: true,
}     }componentWillMount() {
//比如调用了异步请求
const that =this;//因为是异步的,里面的this不是指这个对象了,得在这里存下这个对象
request("xxxx", function(success){
    // 2.setState时候判断下是否被卸载if (that.state.isMounted) {//如果没被卸载,则执行setStatethat.setState({...});
}
})
}
componentWillUnMount() {
// 3.卸载的时候把标志位设置一下
this.state.isMounted = false;
}

以上1,2,3步就阻止了上述情况的发生。


  相关解决方案