Jeremy Ahn
Jeremy Ahn

Reputation: 335

Using setState() with react-navigation gives me "can only update mounted component" issues

As it stands, my app consists of three screens in a StackNavigation setup; first screen leads to the second leads to the third. Only the third screen makes use of setState.

Although the app works impeccably during the first run, issues start to arise as I close the third screen and reopen it another time. I start getting the warning where setState can only update a mounted or mounting component. There are no instances of setState in the mounting functions. Looking this issue up online yields me with surprisingly few results, none of which appear to be helpful for me in this case.

Since I am only using state in a single screen, I couldn't imagine this would be such an issue.

Upvotes: 0

Views: 430

Answers (1)

Tal Avissar
Tal Avissar

Reputation: 10304

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. Please check the code for the undefined component.

This means you can only perform set state on a mounted component.

The way to solve this is by setting a ref to the component and then checking if the ref exists before setting the state.

for example:

fetchUser(){
  if (this.refs.divRef) 
   this.setState({fetchedUser: true});
}

render() {
  return (
    <div ref="divRef">
      {this.state.fetchedUser}
    </div>
  );
}

Upvotes: 3

Related Questions