简体   繁体   English

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

[英]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.

相关问题 React setState只能更新已安装或安装的组件 - React setState can only update a mounted or mounting component React setstate只能在重新渲染时更新已安装或安装的组件 - React setstate can only update a mounted or mounting component — on rerender React JS setState(…):只能更新已安装或正在安装的组件 - React JS setState(…): Can only update a mounted or mounting component React-setState(…)只能更新已安装或正在安装的组件 - React - setState(…) Can only update a mounted or mounting component React-setState(…):只能更新已安装或正在安装的组件 - React - setState(…): Can only update a mounted or mounting component 反应警告:setState(…)只能更新已安装或正在安装的组件 - React Warning: setState(…) Can only update a mounted or mounting component 警告:setState(…):只能更新已安装或正在安装的组件 - Warning react : setState(…): Can only update a mounted or mounting component 反应警告setState(…):只能更新已安装或正在安装的组件 - React warning setState(…): Can only update a mounted or mounting component setState只能更新已安装或安装的组件 - setState Can only update a mounted or mounting component setState(…):只能更新已安装或正在安装的组件 - setState(…): Can only update a mounted or mounting component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM