Skip to content
Source
Sign inSign up
TanStack/query

fix(query-core): propagate AbortSignal reason in infiniteQueryBehavior fetchPage cancellation #10476

Mergedkuishou68(GitHub profile, opens in a new tab)merged 4 commits intomain fromrefs/pull/10476/headmerged by TkDodo View on GitHub

Summary

Fixes #10475

Problem

In infiniteQueryBehavior.ts, the internal fetchPage helper function calls Promise.reject() without any argument when a query cancellation is detected via the cancelled flag (which is set by the AbortSignal abort event listener):

// Before (bug)
const fetchPage = async (data, param, previous) => {
  if (cancelled) {
    return Promise.reject()  // rejects with undefined!
  }
  // ...
}

When query.cancel() → abortController.abort() is called, the abort signal fires and sets cancelled = true. On the next iteration of the multi-page fetch loop, fetchPage rejects with undefined instead of the proper AbortError that is set as context.signal.reason.

Fix

Propagate context.signal.reason as the rejection value, which is a DOMException with name "AbortError" when AbortController.abort() is called without an explicit reason (per the AbortSignal spec):

// After (fix)
const fetchPage = async (data, param, previous) => {
  if (cancelled) {
    return Promise.reject(context.signal.reason)  // proper AbortError DOMException
  }
  // ...
}

Impact

This fixes the following issues that occur when an infinite query is cancelled mid-pagination:

  • Custom retry functions receiving undefined instead of an AbortError
  • QueryCache.onError callbacks receiving undefined as the error argument
  • Error boundaries via throwOnError showing "undefined" errors

Testing

The fix is minimal and targeted. The change ensures that when the AbortSignal fires during a multi-page infinite query fetch, the proper DOMException{ name: "AbortError" } is propagated as the rejection reason, consistent with the Web AbortController specification.

Summary by CodeRabbit

  • Bug Fixes

    • Cancellation now surfaces the underlying abort reason when an in-flight operation is cancelled, improving error diagnostics and debugging.
  • Tests

    • Added a unit test to validate that cancellation propagates the abort reason and that fetch behavior correctly rejects with that reason.
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: query-core

    2. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      📝 Walkthrough

      Walkthrough

      The cancellation path in fetchPage (infiniteQueryBehavior) now rejects with context.signal.reason when aborted. A unit test was added to assert that a cancelled in-flight infinite query surfaces the AbortSignal reason instead of an undefined rejection.

      Changes

      Cohort / File(s)Summary
      Infinite query cancellation change
      packages/query-core/src/infiniteQueryBehavior.ts
      When a page fetch detects cancellation, it now rejects with context.signal.reason instead of rejecting without a value.
      Test covering abort reason propagation
      packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx
      Added a unit test that injects an AbortSignal, triggers cancellation during a page fetch, and asserts the fetch promise rejects with signal.reason and that queryFn call counts are expected.

      Estimated code review effort

      🎯 2 (Simple) | ⏱️ ~10 minutes

      Poem

      🐰 A rabbit hops through code and cheer, A cancelled fetch now speaks sincere, No empty void, no silent cry, The AbortSignal tells us why. 🥕

      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly summarizes the main change: propagating the AbortSignal reason in infiniteQueryBehavior's fetchPage cancellation handler.
      Description check✅ PassedThe description comprehensively covers the problem, fix, impact, and testing approach. However, it does not include the required checklist items from the template (Contributing guide, pnpm test, changeset).
      Linked Issues check✅ PassedThe code changes directly address issue #10475: Promise.reject() now includes context.signal.reason, and a test validates the AbortSignal reason is properly propagated.
      Out of Scope Changes check✅ PassedAll changes are narrowly scoped to fixing the cancellation behavior in infiniteQueryBehavior and adding a corresponding test.
      ✏️ Tip: You can configure your own custom pre-merge checks in the settings.
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    3. TkDodo reviewed

      this looks good, but can you please add the steps-to-reproduce from your issue as a test case? Ideally, that test fails on main but works with your PR. Thanks.

    4. Thanks for the review, @TkDodo! I'll add a test case that reproduces the issue from #10475.

      The test will demonstrate that when a query is aborted, the retry function and error handlers receive the proper AbortError reason (i.e., context.signal.reason) instead of undefined. I'll push the test shortly — it will fail on main and pass with this PR's change.

    5. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit 4f818c80ee0660ce85154c068e911f889be2c745

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded5m 38sView ↗
      nx run-many --target=build --exclude=examples/*...✅ Succeeded2sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-04-25 16:59:31 UTC

    6. pkg-pr-new[bot](GitHub profile, opens in a new tab)commented
      More templates

      @tanstack/angular-query-experimental

      npm i https://pkg.pr.new/@tanstack/angular-query-experimental@10476

      @tanstack/eslint-plugin-query

      npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@10476

      @tanstack/preact-query

      npm i https://pkg.pr.new/@tanstack/preact-query@10476

      @tanstack/preact-query-devtools

      npm i https://pkg.pr.new/@tanstack/preact-query-devtools@10476

      @tanstack/preact-query-persist-client

      npm i https://pkg.pr.new/@tanstack/preact-query-persist-client@10476

      @tanstack/query-async-storage-persister

      npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@10476

      @tanstack/query-broadcast-client-experimental

      npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@10476

      @tanstack/query-core

      npm i https://pkg.pr.new/@tanstack/query-core@10476

      @tanstack/query-devtools

      npm i https://pkg.pr.new/@tanstack/query-devtools@10476

      @tanstack/query-persist-client-core

      npm i https://pkg.pr.new/@tanstack/query-persist-client-core@10476

      @tanstack/query-sync-storage-persister

      npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@10476

      @tanstack/react-query

      npm i https://pkg.pr.new/@tanstack/react-query@10476

      @tanstack/react-query-devtools

      npm i https://pkg.pr.new/@tanstack/react-query-devtools@10476

      @tanstack/react-query-next-experimental

      npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@10476

      @tanstack/react-query-persist-client

      npm i https://pkg.pr.new/@tanstack/react-query-persist-client@10476

      @tanstack/solid-query

      npm i https://pkg.pr.new/@tanstack/solid-query@10476

      @tanstack/solid-query-devtools

      npm i https://pkg.pr.new/@tanstack/solid-query-devtools@10476

      @tanstack/solid-query-persist-client

      npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@10476

      @tanstack/svelte-query

      npm i https://pkg.pr.new/@tanstack/svelte-query@10476

      @tanstack/svelte-query-devtools

      npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@10476

      @tanstack/svelte-query-persist-client

      npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@10476

      @tanstack/vue-query

      npm i https://pkg.pr.new/@tanstack/vue-query@10476

      @tanstack/vue-query-devtools

      npm i https://pkg.pr.new/@tanstack/vue-query-devtools@10476

      commit: 4f818c8

    7. 🧹 Nitpick comments (1)
      packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx (1)

      336-374: Test correctly validates the fix; consider a brief comment on the lazy signal access.

      The test reasoning is sound: with two existing pages in state.data, the refetch path invokes fetchPage twice. The first call lets queryFn run, abort the controller, and resolve with pageParam — which is why queryFn is asserted to be called exactly once. The second fetchPage then short-circuits on the cancelled flag and rejects with signal.reason, which is the behavior this PR introduces.

      Two small notes:

      1. The whole test hinges on void signal.aborted triggering registration of the abort listener inside addConsumeAwareSignal (the listener is only attached on first access of context.signal). Without that line, cancelled would never flip to true and the test would hang/fail for the wrong reason. A one-line comment would save future readers from wondering why a seemingly dead expression is there.
      2. Since signal.reason becomes a stable reference once abort() fires, .rejects.toBe(...) is an appropriately strict assertion (good — it would catch a regression that wraps/rethrows the reason).
      📝 Optional: clarify the intent of the signal access
           const queryFn = vi.fn().mockImplementation(({ pageParam, signal }) => {
      +      // Access `signal` so `addConsumeAwareSignal` registers the abort listener
      +      // that flips the internal `cancelled` flag in fetchPage.
             void signal.aborted
      
             if (pageParam === 1) {
               abortController.abort()
             }
      
             return pageParam
           })
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx` around
      lines 336 - 374, Add a one-line test comment explaining the intentional lazy
      access of the AbortSignal (the `void signal.aborted` expression) so future
      readers know it's required to trigger `addConsumeAwareSignal`'s listener
      attachment; place the comment immediately above the `void signal.aborted` line
      inside the test "should surface the abort reason when cancellation happens
      between refetched pages" next to the `queryFn` mock setup to clarify the purpose
      of that seemingly no-op access.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against the current code and only fix it if needed.
      
      Nitpick comments:
      In `@packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx`:
      - Around line 336-374: Add a one-line test comment explaining the intentional
      lazy access of the AbortSignal (the `void signal.aborted` expression) so future
      readers know it's required to trigger `addConsumeAwareSignal`'s listener
      attachment; place the comment immediately above the `void signal.aborted` line
      inside the test "should surface the abort reason when cancellation happens
      between refetched pages" next to the `queryFn` mock setup to clarify the purpose
      of that seemingly no-op access.

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      Run ID: 5c3d3549-9ed0-4462-a639-43b608ee75eb

      📥 Commits

      Reviewing files that changed from the base of the PR and between 2163c11c8066021553bd8050dedba59c654e9a0e and 4f818c80ee0660ce85154c068e911f889be2c745.

      📒 Files selected for processing (1)
      • packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx
    8. TkDodo merged this672c319

    9. TkDodo closed this

Sign in to join this conversation.