关于javascript:当我的React应用程序中的路线发生更改时,我clearInterval()和应用程序中断

when route changes in my React app I clearInterval() and app breaks

我正在使用React-router-dom开发一个React应用程序。

我有一个菜单,其中包含一些react-router-dom的,每个菜单都将我带到不同的路线。

在我的主要路线path="/"中,我有一个chartComponent,它的图表不断随随机数据而变化,例如:this.chartChangeId = setInterval(()=> this.setState(data), 1500)

在我添加以下内容之前:

1
2
3
componentWillUnmount(){
    clearInterval(this.chartChangeId);
}

到chartComponent我的应用程序没有中断,但是出现了以下错误:

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.
Please check the code for the BrainWaveChart component.

所以我将其添加到生命周期中。

但是现在,当我单击之一转到另一条路线时,我的应用程序中断了,并且出现此错误:

Uncaught TypeError: timeout.close is not a function
at exports.clearTimeout.exports.clearInterval (main.js:14)
at BrainWaveChart.componentWillUnmount (brainwaveChart.jsx:116)
at callComponentWillUnmountWithTimer (vendor_f02cab182c1842c98837.js:45235)
at HTMLUnknownElement.callCallback (vendor_f02cab182c1842c98837.js:37015)
at Object.invokeGuardedCallbackDev (vendor_f02cab182c1842c98837.js:37054)
at invokeGuardedCallback (vendor_f02cab182c1842c98837.js:36911)
at safelyCallComponentWillUnmount (vendor_f02cab182c1842c98837.js:45242)
at commitUnmount (vendor_f02cab182c1842c98837.js:45368)
at commitNestedUnmounts (vendor_f02cab182c1842c98837.js:45404)
at unmountHostComponents (vendor_f02cab182c1842c98837.js:45687)

我做错了吗?


即使清除间隔,()=> this.setState(data)仍在执行,因为间隔已在内存中且位于异步堆栈中。 您需要做的是检查组件是否存在,然后再更新状态。 最简单的方法是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const {clearInterval, setInterval} = window;
class Comp extends React.Component {
  constructor(props) {
    super(props);
    this.mounted = false;
    this.interval = setInterval(() => {
      if(this.mounted) this.setState();
    })
  }
  componentWillMount() {
    this.mounted = true;
  }
  componentWillUnmount() {
    this.mounted = false;
    clearInterval(this.interval);
  }
}

但是,这更像是反菜式。 正确的方法是根本不使用Ajax中的setState。 https://reactjs.org/blog/2015/12/16/ismount-antipattern.html


您的IDE可能会自动为您导入{ clearInterval }
这就是导致问题的原因。
请检查文件中是否有import { clearInterval } from ....语句,
并删除它。
它发生在某些IDE中。
该链接提供了更多信息:
https://github.com/angular/angular/issues/12400