使用reactjs遇到Warning: setState(...): Can only update a mounted or mounting component.

前端数据大部分都来源于后端,我们在页面刚渲染的时候发起异步请求,然后在返回结果中进行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({
        .....
    });
}
 

猜你喜欢

转载自blog.csdn.net/weixin_42046201/article/details/81484145