首页 > 解决方案 > 使用 React Router 切换到不同组件时出现随机内存泄漏错误

问题描述

这个错误并非每次都会发生,但它会弹出足以让我的应用程序担心。目前,我有一个容器来处理我所有的 HTTP 请求,它通过像这样轮询服务器来做到这一点:

  componentDidMount(){
    this.timer = setInterval(() => [this.getData(), this.getCustData()], 1000);
  }

  componentWillUnmount(){
    this.timer && clearInterval(this.timer);
    this.timer = false
  }
  getData = () => {
      axios.get('http://localhost:3001/api/v1/pickup_deliveries')
        .then((response) => {
            this.setState({
              apiData: response.data
            })
          })
        .catch((error)=>{console.log(error);});
  }

我使用 React Router 转到另一个也使用 HTTP 请求的容器,但这与执行轮询的容器无关(我将很快用 redux 解决这个问题,但我还没有实现它)。基本上,当我卸载组件时,轮询应该(并且确实)停止。问题是,有时当我切换到下一个组件时,我会在转换中遇到错误。就像它在一秒的时间间隔内被捕获并导致短暂的内存泄漏。:

index.js:1437 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.
    in PickupDeliveriesForm (created by Wrapper)
    in div (created by Wrapper)
    in Wrapper (at PickupDeliveries.js:200)
    in div (at PickupDeliveries.js:197)
    in div (at PickupDeliveries.js:196)
    in PickupDeliveries (created by Context.Consumer)

这是一个主要问题吗?我是否应该担心随机内存泄漏,或者当我尝试卸载正在轮询服务器的组件时是否会出现这种情况setInterval

标签: reactjshttpaxiospollingunmount

解决方案


推荐阅读