在运行react项目的时候有时会报一个红色的warning,如下图
在这里插入图片描述
Warning: 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状态更新。这是一个无操作,但它表明您的应用程序中存在内存泄漏。要修复此问题,请取消componentWillUnmount方法中的所有订阅和异步任务

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

解决方案:在componentWillUnmount生命周期方法中取消未完成的请求或者其他操作

/**
   * @Author: Lq
   * @description: 在组件销毁前撤销异步请求
   */  
  componentWillUnmount() {
    this.setState = () => {
      return;
    }
  }
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐