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

Last updated : July 24, 2022

This error usually happens when you call the React setState method in a Class component's constructor. The reason is that the component state is not yet initialized when the constructor is called.

This code will cause the warning Can't call setState on a component that is not yet mounted because it tries to access the setState method in the component state that is not initialized yet.

constructor(){
    super(props)
    //this.state is undefined at this point
    this.setState({hasError : false})
}

To fix the warning, initialize the state in the Class constructor.

constructor(){
    super(props)
    //initialize the state with the variable
    this.state = ({hasError : false})
}

This warning can also happen if you call a method from the Class constructor that sets the state using setState.

constructor(){
    super(props)
    this.callApi("api_url")
}
callApi(url: string){
    //This statement is called from the constructor. Therefore, the 
    //component state is not yet initialized
    this.setState({didReceiveResponse: false})
}

Use componentDidMount or componentWillMount lifecycle methods to call any methods that set the state using setState.

constructor(){
    super(props)
    //Move this method in to componentDidMount or componentWillMount
    //this.callApi("api_url")
}
componentWillUnmount(){
    this.callApi("api_url")
}
callApi(url: string){
    this.setState({didReceiveResponse: false})
}
L Raney
By: L Raney
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Comments are disabled

No Comments