Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async SetState in componentDidMount() warning in React Native

The warning message says:

"Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op."

The code caused it:

async componentDidMount() {
  const token = await AsyncStorage.getItem('google_token');

  if (token) {
    this.props.navigation.navigate('feed');
    this.setState({ token });
  } else {
    this.setState({ token: false });
  }
 }

After some google, I'm really confused on if I should be worried about this warning. How can I get the warning message away without disabling the rule like this Github issue suggested ?

like image 620
zenoh Avatar asked Nov 26 '25 03:11

zenoh


1 Answers

I think the issue is that you're navigating to 'feed' then updating the state on this component. It might be a better idea to update the state first then navigate once its completed:

async componentDidMount() {
  const token = await AsyncStorage.getItem('google_token');

  if (token) {
    this.setState({ token }, () => this.props.navigation.navigate('feed'));
  } else {
    this.setState({ token: false });
  }
 }
like image 54
Matt Aft Avatar answered Nov 28 '25 16:11

Matt Aft