Javascript 反应:设置状态只能更新已安装或正在安装的组件

Javascript 反应:设置状态只能更新已安装或正在安装的组件,javascript,reactjs,components,Javascript,Reactjs,Components,我需要在我的组件中的超时内设置一个setState,因此我已完成以下操作: componentDidMount() { this.timeouts.push(setTimeout(() => { this.setState({ text: 2 }); }, 4000)); } componentWillUnmount() { this.timeouts = []; } 但我得到了一个错误: Warning: setState(...): Can only updat

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

我做错了什么?

更改您的
组件将卸载
以正确清除超时。您需要使用
clearTimeout
来清除超时,而不是清空数组

componentDidMount() {
  this.timeouts.push(setTimeout(() => {
    this.setState({ text: 2 });
  }, 4000));
}

clearTimeouts: function() {
  this.timeouts.forEach(clearTimeout);
}

componentWillUnmount() {
  this.clearTimeouts();
}

在调用setState之前,将安装组件,但未安装组件mounted@MatheusLima当您的setState被调用时,您的组件被卸载,不要忘记您正在使用timeout!你的组件会在4秒钟内卸载吗?@NickZuber我想就是这个了!我可能没有正确地卸下它。我将更新问题。卸载组件时,您应该清除超时,我认为@IhorSkliar是正确的