[componentWillUnmount ]React组件销毁中清理异步操作和取消请求

react一直报这个错误:Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

原因:

通常是 react 组件已经从 DOM 中移除(有时候是热更新引起的),但是我们在组件中做的一些异步操作还未结束,如:接口调用或者是一个setState的异步操作等,当其完成时,而此时我们已经将改组件dom移除,从而导致上述问题。

解决办法:

componentWillUnmount() {
  this.setState = (state, callback) => {
    return
  }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容