Jack23
Jack23

Reputation: 1396

Can't perform a React state update

I have this kind of error:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

I have tried to follow some advice that I found but I haven't solved it. How can I do??

class Starting extends Component {
  _isMounted = false
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
    };
  }

  componentDidMount() {
  this._isMounted = true;
   User.getUserLoggato()
     .then(dataUserLoggato => {
        if (dataUserLoggato !== null) {
          global.user = new User(JSON.parse(dataUserLoggato));
          Actions.homepage({ utente: global.user });
        } else {
          Actions.login();
       }
      })
      .catch(err => {
        console.log(err);
      })
      .finally(() => {
        this.setState({ loading: false });
      }); 
  }

  componentWillUnmount() {
    this._isMounted = false;
  }


  render() {
    return (
      <View style={style.container}>
        <View style={style.page}>
        <ActivityIndicator size="large" color="#56cbbe" />
      </View>
      </View>
    );
  }
}

Upvotes: 0

Views: 214

Answers (1)

CD..
CD..

Reputation: 74096

Check if the component is mounted before you set the state:

 .finally(() => {
    this._isMounted && this.setState({ loading: false });
  }); 

Upvotes: 3

Related Questions