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

Last updated : Jul 30, 2023 12:00 AM

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})
}
Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...