Hacktoberfest 2026:メンテナが10月に向けて印を付けた、オープンで初心者向けの issue。 Hacktoberfest の issue を見る

`createQuery`/`createQueries`: a `queryFn` that reads reactive state before its first `await` causes an infinite observer teardown/refetch loop

オープン
#11,541 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

評価

難易度
3/5
見積もり時間
1〜2日
初心者へのやさしさ
78/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
typescript

調査の方向性

packages/svelte-query/tests/createQuery/createQuery.svelte.test.ts から始め、createQuery に対して提供されているリグレッションテストを追加または実行します。createBaseQuery のサブスクリプションエフェクトを読み、追跡対象の observer の読み取りを維持しながら、observer.subscribe がリアクティブトラッキングの対象にならないようにします。完了の条件は、fetch が 1 回だけ行われ、ステータスが成功し、データが反映され、217 個すべてのテストがパスすることです。

索引モデルが issue の本文から書いたものです。

説明

Describe the bug

A queryFn that reads any reactive state ($state) synchronously — before its first await — silently adds that state to the dependencies of the internal subscription $effect in createQuery/createQueries. Every subsequent write to that state re-runs the effect: the observer is torn down (cancelling any in-flight fetch) and re-subscribed. If the fetch takes longer than the interval between writes, the query never receives data, and since it stays dataless every re-subscription starts a new fetch via shouldFetchOnMount — an unbounded fetch loop.

The root cause: the subscription effect calls observer.subscribe(...). For a query without data, query-core executes queryFn synchronously inside that call (onSubscribeshouldFetchOnMount#executeFetchQuery.fetch → retryer → queryFn), i.e. inside the effect's tracking scope. Reactive reads performed in that window (everything before the queryFn's first await) are recorded as dependencies of the effect.

The full loop requires all of the following, each of which is ordinary app code:

  1. the queryFn reads reactive state before its first await (auth-token store, config store, health store, …);
  2. that state is written while a fetch is in flight (e.g. the fetch's own error/backoff handling marks the store). The resulting teardown cancels the in-flight fetch — this needs the queryFn to consume ctx.signal, which real transports do: Query.removeObserver only performs a real cancel when abortSignalConsumed, otherwise the fetch is allowed to finish and the loop self-heals;
  3. the fetch is slower than the write cadence.

Context / impact

This affects createQuery, createInfiniteQuery (both via createBaseQuery) and createQueries. We hit this in a production app: a queryFn reading coordinator health stores before a signed RPC (~300 ms) drove a sustained loop of ~3.2 cancelled-and-retried signed requests per second, indefinitely — each cancellation having already burned the expensive work. Workaround for apps: wrap reactive reads inside queryFn in untrack() — but since the library executes queryFn inside its own effect, the library should shield that execution.

Your minimal, reproducible example

ts

Steps to reproduce

Self-contained regression test (also included in the companion PR), run against @tanstack/svelte-query@6.2.1 + svelte@5.57.0:

it(
  'should not re-subscribe when queryFn reads reactive state before its first await',
  withEffectRoot(async () => {
    const key = queryKey()
    const tick = ref(0)
    const fetches: Array<number> = []

    const query = createQuery<number, Error>(
      () => ({
        queryKey: key,
        queryFn: async (ctx) => {
          void ctx.signal // consume the abort signal, like real transports do
          const startedAt = tick.value // reactive read before the first await
          fetches.push(startedAt)
          await sleep(150)
          tick.value = startedAt + 1 // write mid-flight (e.g. a health mark)
          await sleep(150)
          return startedAt
        },
      }),
      () => queryClient,
    )

    await vi.advanceTimersByTimeAsync(1000)

    expect(fetches.length).toBe(1)
    expect(query.data).toBe(0)
    expect(query.status).toBe('success')
  }),
)

Steps to reproduce

  1. Add the test above to packages/svelte-query/tests/createQuery/createQuery.svelte.test.ts on main and run pnpm test:lib.
  2. Observed on current main: fetches.length is 7 (and keeps growing with more simulated time), query.status stays pending, data never lands.

Expected behavior

Exactly one fetch; the write to tick must not re-run the internal subscription effect — the queryFn's reactive reads should not become dependencies of the library's effect.

Suggested fix

Keep the observer read tracked, but run the subscription itself untracked:

$effect(() => {
  const o = observer
  const unsubscribe = isRestoring.current
    ? () => undefined
    : untrack(() => o.subscribe(() => update(createResult())))
  return unsubscribe
})

One subtlety worth noting: the naive untrack(() => observer.subscribe(...)) is wrong — it also untracks the observer read, so changing queries would no longer re-subscribe. The existing test "should track queries added to an initially empty array" catches this, which is why the const o = observer read must stay outside the untrack. With the corrected fix, all 217 tests pass (215 existing + the 2 regression tests from the PR).

Expected behavior

The internal subscription effect must not gain dependencies from the queryFn's execution. Reading reactive state inside a queryFn (before its first await) is ordinary usage and should not re-run the subscription effect — so a write to that state must not tear the observer down or cancel the in-flight fetch. The regression test above should observe exactly one queryFn invocation, query.status === 'success', and the fetched data landing.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

jsdom via vitest, and Chromium (real app)

Tanstack Query adapter

None

TanStack Query version

6.2.1 (latest at time of writing; also verified on 6.1.33)

TypeScript version

6.0.3

Additional context

No response

主要言語
TypeScript
スター
50.3k
フォーク
4.2k
平均マージ
21時間 46分
マージ済み PR(30日)
205

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

TanStack/query のほかの issue

TanStack/query の issue をすべて見る

似ている issue

TypeScript の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。