【发布时间】:2018-08-07 11:32:41
【问题描述】:
Warning: Can't call setState (or forceUpdate) 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.
为什么我仍然收到有关在未安装组件中设置状态的错误?在错误跟踪中,它指向foo() 中的setTimeout。我在执行我的 api 调用之前清除了我的异步计时器并添加了一个检查 - 我看不到这个警告来自哪里。
componentDidMount() {
this.setState({alive: true});
this.foo();
}
componentWillUnmount() {
this.setState({alive: false, timer: 0});
}
foo() {
if (!this.state.alive) return;
fetch('/api/etc/', {method: 'GET', headers: {'Cache-Control': 'no-cache'}})
.then(res => res.json())
.then(json => {
if (!json.length) return;
this.setState((prevState) => ({
timer: setTimeout(this.foo.bind(this), 500)
});
});
}
【问题讨论】:
-
你永远不会在任何地方清除计时器。不要在
componentWillUnmount中调用setState,如果需要,只需调用clearTimeout。 -
这行得通,谢谢。无论我读到什么,都将计时器设置为 0。
标签: javascript reactjs