0

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?

2
  • or maybe stackoverflow.com/a/69837630/4826457 Commented Aug 19 at 15:02
  • This is the right way. I believe the problem is not reproducible, the warning is supposed to disappear, currently it can debugged only on your side when setData is called and whether another piece of code is responsible for this warning. Please, provide a way to reproduce if it persists. Make sure that axios version that you use supports signals. The warning was removed in the latest versions, this isn't a real leak most times Commented Aug 19 at 15:05

1 Answer 1

2

I think the problem description is misleading, I haven‘t seen cases so far where a missing cleanup caused OOM problems. Cleaning up asynchronous effects is mainly about unnecessary resource usage, usually network bandwidth and potentially CPU usage, sometimes causing visible UI lags that could be avoided. Your fix should generally solve that problem.

There is a minor gap in the implementation though, if the cancellation happens after the request finished and the returned Promise is already resolved, but resolution handlers did not yet run, then setData will be called regardless of the cancellation. You could fix that, or just ignore the warning:

if (!controller.signal.cancelled) setData(…); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.