Skip to main content

What does abort() do in a thunk?

Short answer

In Redux Toolkit, abort() is used to cancel the execution of an async thunk.

It stops the async process (for example, a fetch) and triggers the rejected state with the reason "Aborted".


Where abort() is used

The abort() method is available inside the function you pass to createAsyncThunk:

javascript
const fetchUser = createAsyncThunk( 'user/fetch', async (id, { signal, rejectWithValue }) => { const controller = new AbortController() signal.addEventListener('abort', () => controller.abort()) try { const res = await fetch(`/api/users/${id}`, { signal: controller.signal }) return await res.json() } catch (err) { if (err.name === 'AbortError') { return rejectWithValue('The request was aborted') } throw err } } )

Now - if this thunk gets cancelled, RTK will call controller.abort() and the fetch will be interrupted.


How abort() works inside Redux Toolkit

When you create a thunk through createAsyncThunk, RTK adds to it:

  • a special abortController object;
  • a signal you can listen to;
  • and an abort() method you can call manually.
javascript
const promise = dispatch(fetchUser(5))

promise is not just a plain Promise! It has methods:

javascript
promise.abort() promise.unwrap()

Example: how to cancel an async thunk

javascript
const promise = dispatch(fetchUser(5)) // somewhere later... promise.abort()

What happens:

  1. Redux Toolkit calls AbortController.abort()
  2. All fetch requests "tied" to the signal are interrupted
  3. The thunk does not transition to fulfilled
  4. Instead, rejected fires with the error "Aborted"

What happens under the hood

Here is, simplified, how RTK does this internally:

javascript
function createAsyncThunk(typePrefix, payloadCreator) { return (arg) => (dispatch, getState, extra) => { const abortController = new AbortController() const thunkPromise = new Promise(async (resolve, reject) => { try { const result = await payloadCreator(arg, { signal: abortController.signal, dispatch, getState, }) dispatch({ type: `${typePrefix}/fulfilled`, payload: result }) resolve(result) } catch (err) { if (abortController.signal.aborted) { dispatch({ type: `${typePrefix}/rejected`, error: 'Aborted' }) } reject(err) } }) thunkPromise.abort = () => abortController.abort() return thunkPromise } }

Example: usage in React

javascript
const dispatch = useDispatch() useEffect(() => { const promise = dispatch(fetchUser(5)) return () => { // If the component unmounts → cancel the request promise.abort() } }, [dispatch])

Now, if the component unmounts before the request finishes, fetchUser will automatically be interrupted and will not try to update the state.


Why this matters

ProblemHow abort() solves it
The component unmounted during the requestStops execution so it does not update a component that no longer exists
The user quickly switched tabs / pagesOld requests can be cancelled
A long operation needs to be cancelledabort() instantly interrupts the thunk
Avoids data races ("race conditions")Only the last active thunk keeps running

What a cancelled thunk returns

When you call abort(), createAsyncThunk:

  • dispatches the action { type: '.../rejected', error: { message: 'Aborted' } }
  • does not execute further code
  • returns a Promise that rejects with the error "Aborted"

You can catch it:

javascript
const promise = dispatch(fetchUser(5)) promise .unwrap() .then(data => console.log('OK', data)) .catch(err => { if (err.name === 'AbortError') console.log('Request aborted') })

Summary

WhatDescription
abort()Cancels the execution of an async thunk
Where it is calledOn the Promise returned by dispatch(thunk())
What it doesInterrupts the fetch / async function through AbortController
ResultRedux triggers .../rejected with the error "Aborted"
When it is usefulWhen cancelling requests, changing pages, unmounting a component

Final summary:

The abort() method in a thunk is used to interrupt an async operation, to avoid unnecessary state updates and data races. It works through the built-in AbortController passed via signal, and triggers the thunk's rejected state with the error "Aborted".

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.