React异步请求数据出现setState(...): Can only update a mounted or mounting component...

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()操作,在React的官网里有一个解决这个办法的方案,isMounted
原因:

Such situations most commonly occur due to callbacks, 
when a component is waiting for some data and gets unmounted before the data arrives. 
Ideally, any callbacks should be canceled in componentWillUnmount, prior to unmounting.

大概意思是这种情况会出现在callback中,我们的异步请求返回数据之前,组件可能就已经被卸载了,等数据回来再使用setState就会报出上面的警告,所以我们应该手动在componentWillUnmount里去取消callback在它被unmounting之前。
解决办法:

Just set a _isMounted property to true in componentDidMount 
and set it to false in componentWillUnmount, and use this variable to check your component's status.

很好理解,我们使用一个标志位_isMounted,在componentDidMount里设置为true,在componentWillUnmount里设置为false,仅当_isMountedtrue即还未被卸载,才执行setState()
我的代码:

componentWillMount() {
        this._isMounted = true
        fetch('网络请求').then (status, response)=>{
          if (this._isMounted) {
            this.setState({
                activityTipsImg: response.data.tips_url,
                activityTipsContent: response.data.tips_content
            })
          }
        });
}
componentWillUnmount() {
        this._isMounted = false
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文解读了react生命周期的源码,如果你还是个入门的小白,当然可以忽略源码,看一看作者写的demo。也可以明白生...
    Dabao123阅读 1,345评论 0 4
  • 自己最近的项目是基于react的,于是读了一遍react的文档,做了一些记录(除了REFERENCE部分还没开始读...
    潘逸飞阅读 3,506评论 1 10
  • 组件的生命周期方法分以下三个阶段。 Mounting当创建组件的实例并将其插入到DOM中时,将调用这些方法:con...
    _八神光_阅读 1,120评论 0 0
  • 这两天呆在家里,多亏有它做伴儿, 稍有空气异味儿,立马发红色警报, 一会儿又变黄色,最后恢复到绿色, 清除室内异味...
    梦想917阅读 239评论 0 2
  • 人的内心永远是无限制出新的泉眼,在不断的矛盾中求得更多的未知事物。 比如说,我从不知道我是这样的人,而今已经变成了...
    无叹阅读 323评论 0 0