Hello everyone!
While coding with ReactJs you can face countless errors and warnings but this two occurs most frequently.
Error 1.
Can't perform a React state update on an unmounted component solution
The complete error code looks like this:
As you can see from the error message above, the error causes a memory leak in your app and somehow causes your app to re-render multiple times.
To fix this error, you have to cancel all subscriptions and asynchronous task in useEffect hook and/or componentDidMount lifecycle method.
Solution for the error in useEffect() hook.
You can declare let isMounted = true
inside useEffect, which will be changed in the cleanup callback, as soon as the component is unmounted. Before state updates, you now check this variable conditionally:
useEffect(() => {
let isMounted = true; // note this flag denote mount status
someAsyncOperation().then(data => {
if (isMounted) setState(data);
})
return () => { isMounted = false }; // use effect cleanup to set flag false, if unmounted
});
Or
useEffect(() => {
let isMounted = true;
const someFunction = async() => {
await someOperations
}
return () => { isMounted = false };
});
PS: This solution was originally provided by Ford04 on this thread on Stackoverflow
Solution for the error in React componentDidMount and componentWillUnmount lifecycle methods
class Home extends Component {
_isMounted = false;
constructor(props) {
super(props);
this.state = {
news: [],
};
}
componentDidMount() {
this._isMounted = true;
ajaxVar
.get('https://domain')
.then(result => {
if (this._isMounted) {
this.setState({
news: result.data.hits,
});
}
});
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
...
}
}
PS: This solution was originally provided by Vinod on this thread on Stackoverflow
Error 2.
Can't find variable of Alert (or other variable name)
The complete error code looks like this:
This error comes up when you forget to import a variable, a module, a function or a class.
Solution for the error
- Check to see if you have imported all the variables you need in your app.
- Check to see if you have created the class or function that you are referencing.
- Check if you have misspelled a particular import.
If you read to this part, it means that you found this article useful. Kindly leave a feedback and follow me to stay updated on tips like this.
Thank you
#2Articles1Week