Matheus Lima
Matheus Lima

Reputation: 2143

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:

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?

Upvotes: 2

Views: 6530

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281726

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

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

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

componentWillUnmount() {
  this.clearTimeouts();
}

Upvotes: 7

Related Questions