Keltouma Indtaher
Keltouma Indtaher

Reputation: 303

Can't call setState on a component that is not yet mounted - react native

Keep getting the following error message in React Native, really don't understand where it is coming from

Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = {}; class property with the desired state in the ConnectionMqtt component.

constructor(){
    super();
    this.onMessageArrived = this.onMessageArrived.bind(this)
}

componentDidMount() {
    const conn = new ConnectionMqtt();
    conn.onMessageArrived = this.onMessageArrived;
  }

Upvotes: 0

Views: 152

Answers (1)

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

You should not use setState in the constructor since the component is not mounted yet. In this case clickMe() method calls setState(). Instead, initialize the state directly. Like,

constructor(props) {
    super(props);
    // Don't call this.setState() here!
    this.state = { counter: 0 };
    this.handleClick = this.handleClick.bind(this);
}

example if from https://reactjs.org/docs/react-component.html#constructor

Upvotes: 1

Related Questions