繁体   English   中英

React:setState只能更新已安装或安装的组件

[英]React: setState can only update a mounted or mounting component

我的组件中需要一个超时内的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.

我究竟做错了什么?

更改componentWillUnmount以正确清除超时。 您需要使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM