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

时间:2017-03-02 14:07:23

标签: javascript reactjs components

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

我做错了什么?

1 个答案:

答案 0 :(得分:7)

更改componentWillUnmount以正确清除超时。您需要使用clearTimeout来清除超时而不是清空数组。

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

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

componentWillUnmount() {
  this.clearTimeouts();
}