首页 > 解决方案 > 由于“状态更新”,React 已安装组件 setInterval 未清除间隔

问题描述

我为一个函数设置了一个间隔计时器,该函数将今天的日期设置为我初始化的状态componenteDidMount。虽然我清除了componentWillUnmount.

这是错误:

警告: 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.

我曾尝试_isMounted在整个周期中将私有变量从 false 操作为 true,并在setTodaysDate()设置状态之前强制进行条件检查,但即使这样也没有解决问题。

  // _isMounted = false;  <----- tried this method to no avail

  state = {
    selectedDate: ""
  };

  componentDidMount() {
    this.setTodaysDate();
    this.interval = setInterval(() => this.setTodaysDate(), 40 * 1000 * 360);
    // this._isMounted = true;  <----- tried
  }


  componentWillUnmount() {
    clearInterval(this.interval);
    // this._isMounted = false;  <----- tried
  }


  setTodaysDate = () => {
    // if (this._isMounted) {  <----- tried
    this.setState({
      selectedDate: moment(moment(), "YYYY-MM-DDTHH:mm:ss")
        .add(1, "days")
        .format("YYYY-MM-DD")
    });

    // }  <----- tried

  }

我不知道如何“堵塞泄漏”。

编辑:事实证明,多亏了下面的 Gabriele,真正的原因是我使用的 lodash debounce 方法(我也在其中 setState)在卸载期间从未取消,导致“泄漏”:

  debounceCloseAlert = _.debounce(() => {
    this.setState({ alertVisible: false });
  }, 5000);

标签: javascriptreactjs

解决方案


查看您的组件,我认为问题不在于您的setInterval. 您处理它的方式是正确的方法,不应产生上述错误。

我认为问题在于_.debounce在您的debounceCloseAlert方法中使用。它还会创建一个超时,您不会在任何地方清除它。

from 返回的值_.debounce包括一个.cancel()清除间隔的方法。所以只要打电话给this.debounceCloseAlert.cancel();componentWillUnmount,它就会清除它。


推荐阅读