Skip to content
Source
Sign inSign up
TanStack/query

fix(svelte-query): unsubscribe the observer when its effect root is disposed #11597

ClosedNeekoras(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/11597/headopened View on GitHub

🎯 Changes

Fixes #11587.

A query created inside $effect.root stays subscribed after the root's disposer runs. The observer is never released, so the cache entry survives its gcTime, interval refetches keep firing, and a pending request that uses its AbortSignal is never aborted.

createBaseQuery subscribes eagerly, outside any effect, so that the subscription exists on the server and on suspended branches. Two things are meant to tear that subscription down later:

  • the watchChanges effect on [isRestoring.current, observer], which returns a cleanup, but only from its second run, since the helper skips the first invocation
  • onDestroy, which throws outside a component and is swallowed by the surrounding try

Inside $effect.root neither applies, so the first subscription has no teardown. This adds one effect whose only job is to unsubscribe on teardown, which the root disposer runs. In a component it is redundant with onDestroy, and unsubscribing twice is a no-op. It is in a try for the same reason as the onDestroy next to it: outside an effect context the call throws, and that should not become an error for callers. During SSR the effect does not run and onDestroy still handles cleanup.

Tests

packages/svelte-query/tests/createQuery/observer-cleanup.svelte.test.ts is the reproducer from the issue, written by @Osraka, included with their commit as the source. It covers createQuery and createInfiniteQuery in the success, error and disabled states, disposal before the first effect runs, signal abortion, interval refetches, and two controls that already passed: normal component unmount and disposal after switching clients.

  • Before: 10 failed, 2 passed, matching the issue.
  • After: 12 passed. Whole package: 24 files, 226 tests, no type errors.
  • test:eslint, test:lib, test:types, test:build and build pass for @tanstack/svelte-query, and test:sherif, test:knip and test:docs pass for the repository. (pnpm run test:pr itself hung with no output on my machine before running anything, so I ran its targets directly.)

On #11542 and #11557: both branch from before #9810, so this reproducer passes there only because their base predates the regression. Neither merges onto current main without a conflict in this file, and both target different symptoms.

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested code changes locally with pnpm run test:pr, or these tests do not apply to this pull request.
  • I fully understand the code in this pull request, including any code generated with AI assistance.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Summary by CodeRabbit

  • Bug Fixes

    • Query observers now unsubscribe when their effect root is disposed, including after successful, failed, or disabled queries.
    • Disposing a root also stops interval refetches and aborts requests that use cancellation signals. Cleanup continues to work on component unmount and when the client changes.
  • Tests

    • Added coverage for observer cleanup, resource disposal, and garbage collection.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration

      Configuration used: Repository: TanStack/query/.coderabbit.yaml

      Review profile: CHILL

      Plan: Advanced

      Run ID: ef3234d3-878d-482d-9a1e-3197f5316750

      📥 Commits

      Reviewing files that changed from the base of the PR and between 32ca5b50d4f646b489bc57100767990ef55718c7 and a9299409785cfd87c14c3d636bfd32b866b6d35a.

      📒 Files selected for processing (3)
      • .changeset/svelte-query-effect-root-cleanup.md
      • packages/svelte-query/src/createBaseQuery.svelte.ts
      • packages/svelte-query/tests/createQuery/observer-cleanup.svelte.test.ts

      Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


      📝 Walkthrough

      Walkthrough

      createBaseQuery now registers an $effect.pre cleanup for its initial observer subscription. Tests cover disposal of effect roots and related observer cleanup behavior. A changeset declares a patch release for @tanstack/svelte-query.

      Changes

      Svelte query cleanup

      Layer / File(s)Summary
      Effect-root observer cleanup
      packages/svelte-query/src/createBaseQuery.svelte.ts, packages/svelte-query/tests/createQuery/observer-cleanup.svelte.test.ts, .changeset/svelte-query-effect-root-cleanup.md
      createBaseQuery adds an $effect.pre cleanup that calls unsubscribe() and retains the onDestroy cleanup. Tests cover observer removal, cache garbage collection, request cancellation, interval refetching, component unmount, and client changes. A changeset declares a patch release.

      Estimated code review effort: 2 (Simple) | ~10 minutes

      Merge Risk: ⚪ Minimal · up to a9299

      The observer cleanup appears ready to merge after normal checks; no unresolved behavior issue was identified.

      🚥 Pre-merge checks | ✅ 5
      ✅ Passed checks (5 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly and concisely identifies the main change: unsubscribing the Svelte Query observer when its effect root is disposed.
      Description check✅ PassedThe description includes the required Changes, Checklist, and Release Impact sections. It explains the defect, implementation, tests, release impact, and the limitation that pnpm run test:pr hung whil…
      Linked Issues check✅ PassedThe change satisfies the coding requirements in [#11587]. createBaseQuery.svelte.ts keeps the eager observer.subscribe call and adds an $effect.pre cleanup for root disposal. The existing `onDes…
      Out of Scope Changes check✅ PassedThe changes stay within [#11587]. The source change implements observer cleanup. The tests verify the linked behavior and preserve control cases. The changeset declares the required package patch rele…
      Docstring Coverage✅ PassedDocstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 2 files. (1 skipped: 1 …
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create a new PR

      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.

Sign in to join this conversation.