Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous code example
Example 1: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
## Description
This issue usually happens when you're trying to apply state
changes to a component that does not exists anymore.
Often happens when the component gets removed from a tree
while there is a promise running in one of it's lifecycles.
The best way to fix it is to make sure that if there is any
promises in your component lifecycle, it should abort those
once the component gets unmounted from the tree.
Here is an interesting article that gives you a reproduction of this
error together with one type of solution https://www.debuggr.io/react-update-unmounted-component/
Example 2: Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
function useIsMountedRef(){ const isMountedRef = useRef(null); useEffect(() => { isMountedRef.current = true; return () => isMountedRef.current = false; }); return isMountedRef;}
function Pets() {
const [pets, dispatch] = useReducer(petsReducer, initialState);
const isMountedRef = useIsMountedRef();
const onChange = ({ target }) => {
dispatch({ type: "PET_SELECTED", payload: target.value });
};
useEffect(() => {
if (pets.selectedPet) {
dispatch({ type: "FETCH_PET" });
getPet(pets.selectedPet).then(data => {
if(isMountedRef.current){ dispatch({ type: "FETCH_PET_SUCCESS", payload: data });
}
});
} else {
dispatch({ type: "RESET" });
}
}, [pets.selectedPet, isMountedRef]);
return (
<div>
<select value={pets.selectedPet} onChange={onChange}>
<option value="">Select a pet</option>
<option value="cats">Cats</option>
<option value="dogs">Dogs</option>
</select>
{pets.loading && <div>Loading...</div>}
{pets.petData && <Pet {...pets.petData} />}
</div>
);
}