Skip to content
Source
Sign inSign up
TanStack/query

fix(core): do not reject promise right away - only when `promise` gets used #9576

MergedTkDodomerged 4 commits intomain fromrefs/pull/9576/headmerged by TkDodo

TkDodocommented

fixes #8209

Summary by CodeRabbit

  • New Features

    • None.
  • Bug Fixes

    • Prevented premature errors when the experimental prefetch-in-render flag is disabled; errors now occur only if a query’s promise is explicitly accessed.
  • Refactor

    • Switched from eager to lazy error handling to avoid initialization failures and preserve normal behavior unless the promise is used.
    1. Walkthrough

      The change defers rejection of the observer's initial thenable until the tracked result's promise property is accessed. With experimental_prefetchInRender disabled the thenable is created pending and only rejected lazily on promise access; behavior unchanged when the flag is enabled.

      Changes

      Cohort / File(s)Summary
      Lazy promise-access rejection
      packages/query-core/src/queryObserver.ts
      Create #currentThenable as pending when experimental_prefetchInRender is disabled; remove eager rejection in constructor; add a Proxy getter that rejects the pending thenable lazily when the promise property is accessed (uses optional chaining for reject). No public API changes.

      Sequence Diagram(s)

      sequenceDiagram
        participant Consumer
        participant QueryObserver
        participant TrackResultProxy
        participant FeatureFlag
      
        Consumer->>QueryObserver: getResult()
        QueryObserver->>TrackResultProxy: return proxied result
        Consumer->>TrackResultProxy: access "promise"
        TrackResultProxy->>FeatureFlag: check experimental_prefetchInRender
        alt flag disabled
          TrackResultProxy->>QueryObserver: call pendingThenable.reject(Error)
          TrackResultProxy-->>Consumer: rejected thenable / thrown error
        else flag enabled
          TrackResultProxy-->>Consumer: return actual promise
        end

      Estimated code review effort

      🎯 3 (Moderate) | ⏱️ ~20 minutes

      Assessment against linked issues

      ObjectiveAddressedExplanation
      Prevent console error when promise isn’t accessed (#8209)✅

      Poem

      I’m a rabbit in the code tonight, I hide the early noisy bite, The promise waits until you peep, No console yelp to wake from sleep, Hop gentle — lazy errors take flight. 🐇✨

      Tip

      🔌 Remote MCP (Model Context Protocol) integration is now available!

      Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


      📜 Recent review details

      Configuration used: CodeRabbit UI Review profile: CHILL Plan: Pro

      💡 Knowledge Base configuration:

      • MCP integration is disabled by default for public repositories
      • Jira integration is disabled by default for public repositories
      • Linear integration is disabled by default for public repositories

      You can enable these sources in your CodeRabbit configuration.

      📥 Commits

      Reviewing files that changed from the base of the PR and between b507746b04ec93ebefddce1834bd7c2ded807cc8 and 4a51a5452d40e0340fc07dc42ac7cc2362775967.

      📒 Files selected for processing (1)
      • packages/query-core/src/queryObserver.ts (1 hunks)
      ⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
      • GitHub Check: Test
      • GitHub Check: Preview
      🔇 Additional comments (2)
      packages/query-core/src/queryObserver.ts (2)

      270-280: LGTM: Lazy-reject only on result.promise access; guarded to reject once

      This implements the intended behavior change: no immediate rejection, and only reject when the promise property is actually accessed. The pending check prevents repeated rejections. This should eliminate the “Uncaught (in promise)” noise for consumers that never read result.promise.


      270-280: Thenable.reject is correctly narrowed by status Verified in packages/query-core/src/thenable.ts that:

      • Thenable = FulfilledThenable | RejectedThenable | PendingThenable
      • PendingThenable extends Promise & { status: 'pending'; resolve(...); reject(reason): void }
      • Neither FulfilledThenable nor RejectedThenable expose .reject

      TypeScript’s discriminated-union narrowing on status === 'pending' guarantees this.#currentThenable.reject(...) is well-typed. No cast or optional chaining is required here.

      ✨ Finishing Touches
      • 📝 Generate Docstrings
        🧪 Generate unit tests
      • Create PR with unit tests
      • Post copyable unit tests in a comment
      • Commit unit tests in branch `feature/8209-experimental_prefetchInRender-promise-rejection`

      🪧 Tips

      Chat

      There are 3 ways to chat with CodeRabbit:

      • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
        • I pushed a fix in commit <commit_id>, please review it.
        • Open a follow-up GitHub issue for this discussion.
      • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
      • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
        • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
        • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

      Support

      Need help? Create a ticket on our support page for assistance with any issues or questions.

      CodeRabbit Commands (Invoked using PR/Issue comments)

      Type @coderabbitai help to get the list of available commands.

      Other keywords and placeholders

      • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
      • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
      • Add @coderabbitai anywhere in the PR title to generate the title automatically.

      CodeRabbit Configuration File (.coderabbit.yaml)

      • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
      • Please see the configuration documentation for more information.
      • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

      Status, Documentation and Community

      • Visit our Status Page to check the current availability of CodeRabbit.
      • Visit our Documentation for detailed information on how to use CodeRabbit.
      • Join our Discord Community to get help, request features, and share feedback.
      • Follow us on X/Twitter for updates and announcements.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: query-core

    3. View your CI Pipeline Execution ↗ for commit 4a51a5452d40e0340fc07dc42ac7cc2362775967

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded47sView ↗

      ☁️ Nx Cloud last updated this comment at 2025-08-19 09:36:38 UTC

    4. More templates

      @tanstack/angular-query-devtools-experimental

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

      @tanstack/angular-query-experimental

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

      @tanstack/eslint-plugin-query

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

      @tanstack/query-async-storage-persister

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

      @tanstack/query-broadcast-client-experimental

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

      @tanstack/query-core

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

      @tanstack/query-devtools

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

      @tanstack/query-persist-client-core

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

      @tanstack/query-sync-storage-persister

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

      @tanstack/react-query

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

      @tanstack/react-query-devtools

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

      @tanstack/react-query-next-experimental

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

      @tanstack/react-query-persist-client

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

      @tanstack/solid-query

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

      @tanstack/solid-query-devtools

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

      @tanstack/solid-query-persist-client

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

      @tanstack/svelte-query

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

      @tanstack/svelte-query-devtools

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

      @tanstack/svelte-query-persist-client

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

      @tanstack/vue-query

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

      @tanstack/vue-query-devtools

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

      commit: 4a51a54

    5. Sizes for commit 4a51a5452d40e0340fc07dc42ac7cc2362775967:

      BranchBundle Size
      Main
      This PR
    6. Codecov Report

      :x: Patch coverage is 40.00000% with 3 lines in your changes missing coverage. Please review. :white_check_mark: Project coverage is 59.23%. Comparing base (e4f5ce8) to head (4a51a54). :warning: Report is 2 commits behind head on main.

      Additional details and impacted files

      Impacted file tree graph

      @@             Coverage Diff             @@
      ##             main    #9576       +/-   ##
      ===========================================
      + Coverage   45.16%   59.23%   +14.06%     
      ===========================================
        Files         208      137       -71     
        Lines        8320     5561     -2759     
        Branches     1873     1499      -374     
      ===========================================
      - Hits         3758     3294      -464     
      + Misses       4115     1963     -2152     
      + Partials      447      304      -143     
      ComponentsCoverage Δ
      @tanstack/angular-query-devtools-experimental∅ <ø> (∅)
      @tanstack/angular-query-experimental87.00% <ø> (ø)
      @tanstack/eslint-plugin-query∅ <ø> (∅)
      @tanstack/query-async-storage-persister43.85% <ø> (ø)
      @tanstack/query-broadcast-client-experimental24.39% <ø> (ø)
      @tanstack/query-codemods∅ <ø> (∅)
      @tanstack/query-core97.40% <40.00%> (-0.17%):arrow_down:
      @tanstack/query-devtools3.48% <ø> (ø)
      @tanstack/query-persist-client-core79.47% <ø> (ø)
      @tanstack/query-sync-storage-persister84.61% <ø> (ø)
      @tanstack/query-test-utils∅ <ø> (∅)
      @tanstack/react-query95.95% <ø> (ø)
      @tanstack/react-query-devtools10.00% <ø> (ø)
      @tanstack/react-query-next-experimental∅ <ø> (∅)
      @tanstack/react-query-persist-client100.00% <ø> (ø)
      @tanstack/solid-query78.13% <ø> (ø)
      @tanstack/solid-query-devtools∅ <ø> (∅)
      @tanstack/solid-query-persist-client100.00% <ø> (ø)
      @tanstack/svelte-query87.58% <ø> (ø)
      @tanstack/svelte-query-devtools∅ <ø> (∅)
      @tanstack/svelte-query-persist-client100.00% <ø> (ø)
      @tanstack/vue-query71.10% <ø> (ø)
      @tanstack/vue-query-devtools∅ <ø> (∅)
      :rocket: New features to boost your workflow:
      • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
      • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
  • Actionable comments posted: 1

    📜 Review details

    Configuration used: CodeRabbit UI Review profile: CHILL Plan: Pro

    💡 Knowledge Base configuration:

    • MCP integration is disabled by default for public repositories
    • Jira integration is disabled by default for public repositories
    • Linear integration is disabled by default for public repositories

    You can enable these sources in your CodeRabbit configuration.

    📥 Commits

    Reviewing files that changed from the base of the PR and between f1e608bcac59a309f61057faa951bd0fad8f75a1 and d613c2a2049148dac02309208d854c8c663d6c9c.

    📒 Files selected for processing (1)
    • packages/query-core/src/queryObserver.ts (1 hunks)
    🧰 Additional context used
    🧬 Code Graph Analysis (1)
    packages/query-core/src/queryObserver.ts (1)
    packages/query-core/src/thenable.ts (1)
    • PendingThenable (37-37)
    ⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
    • GitHub Check: Preview
    • GitHub Check: Test
    packages/query-core/src/queryObserver.ts lines 270 to 278Outdated
    @@ -272,3 +267,12 @@
    272267 get: (target, key) => {
    273268 this.trackProp(key as keyof QueryObserverResult)
    274269 onPropTracked?.(key as keyof QueryObserverResult)
    270+ console.log('tracking prop', key)
    271+ if (key === 'promise' && !this.options.experimental_prefetchInRender) {
    272+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    273+ ;(this.#currentThenable as PendingThenable<TData>).reject?.(
    274+ new Error(
    275+ 'experimental_prefetchInRender feature flag is not enabled',
    276+ ),
    277+ )
    278+ }

    ⚠️ Potential issue

    Remove debug log; guard rejection to pending thenables; type-safe key check

    • console.log in a hot Proxy.get path will spam user consoles and degrade performance. Remove before merging.
    • Only reject if the thenable is still pending to avoid repeated rejections on subsequent accesses.
    • Be explicit about key type to avoid symbol keys triggering unintended behavior.

    Apply:

    -        console.log('tracking prop', key)
    -        if (key === 'promise' && !this.options.experimental_prefetchInRender) {
    -          // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    -          ;(this.#currentThenable as PendingThenable<TData>).reject?.(
    -            new Error(
    -              'experimental_prefetchInRender feature flag is not enabled',
    -            ),
    -          )
    -        }
    +        if (
    +          typeof key === 'string' &&
    +          key === 'promise' &&
    +          !this.options.experimental_prefetchInRender
    +        ) {
    +          const thenable = this.#currentThenable as PendingThenable<TData>
    +          if (thenable.status === 'pending') {
    +            // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    +            thenable.reject?.(
    +              new Error(
    +                'experimental_prefetchInRender feature flag is not enabled',
    +              ),
    +            )
    +          }
    +        }

    If helpful, I can add unit tests to assert:

    • No rejection occurs when result.promise is not accessed.
    • Rejection occurs exactly once when accessed with the flag disabled.
    • No console output is produced during normal operation.
    📝 Committable suggestion

    ‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

            if (
              typeof key === 'string' &&
              key === 'promise' &&
              !this.options.experimental_prefetchInRender
            ) {
              const thenable = this.#currentThenable as PendingThenable<TData>
              if (thenable.status === 'pending') {
                // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
                thenable.reject?.(
                  new Error(
                    'experimental_prefetchInRender feature flag is not enabled',
                  ),
                )
              }
            }
    🤖 Prompt for AI Agents
    In packages/query-core/src/queryObserver.ts around lines 270 to 278, remove the
    console.log('tracking prop') and replace the current key check with a type-safe
    guard (e.g. ensure typeof key === 'string' && key === 'promise') so symbol or
    non-string keys are ignored; before calling reject, verify the thenable is still
    pending (guard against settled thenables) so rejection happens at most once and
    only for PendingThenable instances; use optional chaining/type narrowing to call
    reject only when the thenable is the pending variant.
  • TkDodo reviewed

    OutdatedResolvedby TkDodo
  • TkDodo reviewed

    OutdatedResolvedby TkDodo
  • TkDodoreplied on packages/query-core/src/queryObserver.ts lines 271 to 276

    right, I need a status check I think:

    4a51a545

  • TkDodo merged thisabab082

  • TkDodo closed this

  • Sign in to join this conversation.