Suggest an editImprove this articleRefine the answer for “What does abort() do in a thunk?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)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"`. **Key point:** it works through the built-in `AbortController` passed via `signal`, to avoid unnecessary state updates and race conditions.Shown above the full answer for quick recall.Answer (EN)Image## 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 | Problem | How `abort()` solves it | |---|---| | The component unmounted during the request | Stops execution so it does not update a component that no longer exists | | The user quickly switched tabs / pages | Old requests can be cancelled | | A long operation needs to be cancelled | `abort()` 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 | What | Description | |---|---| | `abort()` | Cancels the execution of an async thunk | | **Where it is called** | On the Promise returned by `dispatch(thunk())` | | **What it does** | Interrupts the `fetch` / async function through `AbortController` | | **Result** | Redux triggers `.../rejected` with the error `"Aborted"` | | **When it is useful** | When 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"`.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.