admin管理员组

文章数量:1326072

I need a setState inside a timeout in my ponent, so I've done this:

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

ponentWillUnmount() {
  this.timeouts = [];
}

But I'm getting this error:

Warning: setState(...): Can only update a mounted or mounting ponent.
This usually means you called setState() on an unmounted ponent.
This is a no-op.

What am I doing wrong?

I need a setState inside a timeout in my ponent, so I've done this:

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

ponentWillUnmount() {
  this.timeouts = [];
}

But I'm getting this error:

Warning: setState(...): Can only update a mounted or mounting ponent.
This usually means you called setState() on an unmounted ponent.
This is a no-op.

What am I doing wrong?

Share Improve this question edited Mar 2, 2017 at 14:25 Matheus Lima asked Mar 2, 2017 at 14:07 Matheus LimaMatheus Lima 2,1433 gold badges33 silver badges49 bronze badges 13
  • Before you call setState your ponent will be mounted but your ponent is not mounted – Ihor Skliar Commented Mar 2, 2017 at 14:11
  • 1 @MatheusLima when your setState was called, your ponent is unmounted, don't forget you are using timeout! – Ihor Skliar Commented Mar 2, 2017 at 14:15
  • 1 Does your ponent unmount within that 4 second frame? – Nick Zuber Commented Mar 2, 2017 at 14:19
  • 1 @NickZuber I think that this is it! I'm probably not unmounting it properly. I'll update the question. – Matheus Lima Commented Mar 2, 2017 at 14:23
  • 1 You should be clearing the timeouts when you unmount the ponent, and I think @IhorSkliar is right – Shubham Khatri Commented Mar 2, 2017 at 14:24
 |  Show 8 more ments

1 Answer 1

Reset to default 7

Change your ponentWillUnmount to clear the timeouts properly. You need to make use of clearTimeout to clear the timeout instead of emptying the array.

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

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

ponentWillUnmount() {
  this.clearTimeouts();
}

本文标签: javascriptReact setState can only update a mounted or mounting componentStack Overflow