[英]React: setState can only update a mounted or mounting component
I need a setState inside a timeout in my component, so I've done this: 我的组件中需要一个超时内的setState,所以我这样做了:
componentDidMount() {
this.timeouts.push(setTimeout(() => {
this.setState({ text: 2 });
}, 4000));
}
componentWillUnmount() {
this.timeouts = [];
}
But I'm getting this error: 但是我收到了这个错误:
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.
What am I doing wrong? 我究竟做错了什么?
Change your componentWillUnmount
to clear the timeouts properly. 更改
componentWillUnmount
以正确清除超时。 You need to make use of clearTimeout
to clear the timeout instead of emptying the array. 您需要使用
clearTimeout
来清除超时而不是清空数组。
componentDidMount() {
this.timeouts.push(setTimeout(() => {
this.setState({ text: 2 });
}, 4000));
}
clearTimeouts: function() {
this.timeouts.forEach(clearTimeout);
}
componentWillUnmount() {
this.clearTimeouts();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.