Software Engineer · Teacher · Author · Vegan

Aborting Fetch Requests with AbortController

Last reviewed on February 20, 2020

We can abort fetch requests using the AbortController class built into the browser. Note, AbortController is experimental, but browser support is pretty good.

So where might we use this? Let’s say we have a React component that fetches and renders some data. The page loads, the fetch request is made, we get impatient and click to another route which dismounts the component. If we set state when the fetch request resolves on an unmounted component, we will get the following error:

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.

You can simulate this in the following example. The button will toggle the rendering of the ReposCount component when it is clicked. If you click the button to unmount the component before the API call finishes, you will see the “Can’t perform a React state update on an unmounted component” warning in the console.

To fix this so that errors aren’t thrown for impatient users, let’s update the component to use AbortController:

One thing to note is that when we call controller.abort(), the fetch promise rejects with an AbortError. In the example above, we are catching the error and logging “aborted”.

Disclaimer: Any viewpoints and opinions expressed in this article are those of David Tang and do not reflect those of my employer or any of my colleagues.