I\'m new using React, so this might be really simple to achieve but I can\'t figure it out by myself even though I\'ve done some research. Forgive me if this is too dumb.
Before mutating the state, you should first check whether the component is still mounted.
As said above by @SanjiMika, when having an async action that causes this error, it means you are trying to mutate the component's state after it was un-mounted.
react-use provides hooks for that, you've got 2 options:
option #1: useMountedState
// check if isMounted before changing any state
const isMounted = useMountedState();
useEffect(() => {
const asyncAction = executeAsyncAction();
asyncAction.then(result => {
if (isMounted) {
// It's safe to mutate state here
}
});
}, []);
option #2: useUnmountPromise
/* `resolveWhileMounted` wraps your promise, and returns a promise that will resolve
* only while the component is still mounted */
const resolveWhileMounted = useUnmountPromise();
useEffect(async () => {
const asyncAction = executeAsyncAction();
resolveWhileMounted(asyncAction).then(result => {
// It's safe to mutate state here
});
}, []);