Can't perform a state update on an unmounted component.
I understand that this warning happens when the component unmounts before the asynchronous request finishes, and then setState (or in my case setData) is called. React doesn’t allow updating state for a component that no longer exists, which is why the warning appears.
Here’s my initial code:
useEffect(() => { const fetchData = async () => { const res = await axios.get('/api/data'); setData(res.data); // Warning occurs if component unmounts before fetch finishes }; fetchData(); }, []); To fix it, I tried using a cleanup function with an AbortController. My updated code looks like this:
useEffect(() => { const controller = new AbortController(); const fetchData = async () => { const res = await axios.get('/api/data', { signal: controller.signal }); setData(res.data); }; fetchData(); return () => controller.abort(); // Is this the right way? }, []); I expected that returning controller.abort() in the cleanup would stop the request if the component unmounted before the request resolved. However, the warning still appears. Am I missing something here? Is this the correct way to implement a cleanup function with Axios, or should I be handling the request cancellation differently?