我的组件中需要一个超时内的setState,所以我已经这样做了:
componentDidMount() {
this.timeouts.push(setTimeout(() => {
this.setState({ text: 2 });
}, 4000));
}
componentWillUnmount() {
this.timeouts = [];
}
但是我收到了这个错误:
Warning: setState(...): Can only update a mounted or mounting component.
This usually means you called setState() on an unmounted component.
This is a no-op.
我做错了什么?
答案 0 :(得分:7)
更改componentWillUnmount
以正确清除超时。您需要使用clearTimeout
来清除超时而不是清空数组。
componentDidMount() {
this.timeouts.push(setTimeout(() => {
this.setState({ text: 2 });
}, 4000));
}
clearTimeouts: function() {
this.timeouts.forEach(clearTimeout);
}
componentWillUnmount() {
this.clearTimeouts();
}