Backtestsvuerun-20261005-155915#15113

Issue #15113 Merged fix PR #15114 Run 5 Oct 2026 · run-20261005-155915 vuejs/core

SSR memory leak - options API watchers are created and never stopped with async setup()

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches make the same root-cause fix. Before calling `handleSetupResult` in the async setup's `.then` callback, they restore the SSR setup flag. That lets `applyOptions` → `doWatch` see `isInSSRComponentSetup === true`, so it skips plain watchers and registers sync watchers in the SSR context for cleanup. This addresses the issue at its source and is equally correct for the reported scenario.

The code differs in one small way. Patch A always resets the flag to `false` in `finally`. Patch B saves the previous value and restores it. In a microtask continuation the previous value should normally be `false`, so behavior is the same in practice. B's save/restore is still the more defensive pattern, and its comment explains why the flag is restored.

Tests decide the comparison. Both add the issue's reproduction test, which fails before the fix and passes after. Patch A adds a GC-based leak test, but it only runs when `global.gc` is exposed (`describe.skipIf`), so it often won't execute. Patch B adds a second deterministic test for `flush: 'sync'` and `immediate` watchers declared through options. It checks that the immediate watcher fires once during SSR and that neither watcher fires after the render. These are the edge cases where the SSR watcher logic takes different paths: sync watchers are tracked via `__watcherHandles` and stopped after render. That test exercises the cleanup path that prevents retention, which gives broader and always-run coverage of the fix.

Scope is equally tight in both patches. B wins on slightly more careful state handling and stronger, always-executing test coverage of the relevant watcher variants.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

5m 31s

Wall-clock time in the container

Full test suite

No new failures

3,628 passed · 6 skipped · 3,634 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

73vs 76 merged

Changed lines, ours vs merged

Vue version

3.5.40

Steps to reproduce

originally reported in https://github.com/nuxt/nuxt/issues/30782

  1. create an options API component with an async setup(), a computed property that reads shared module-level state, and a watch on that
  2. render it on the server and then mutate the shared state after the render is done
  3. see that the watcher is still active on the server

Reproduction

test('options-api watchers should not be created for async setup components', async () => {
  const open = ref(true)
  const spy = vi.fn()

  const App = defineComponent({
    setup: () => Promise.resolve({}),
    computed: {
      isOpen() {
        return open.value
      },
    },
    watch: {
      isOpen: spy,
    },
    render() {
      return h('div', String(this.isOpen))
    },
  })

  const html = await renderToString(createSSRApp(App))
  expect(html).toBe('<div>true</div>')

  // mutating the state after the request is done should not trigger the watcher
  open.value = false
  await nextTick()
  expect(spy).not.toHaveBeenCalled()
})

What is expected?

the same behavior as with a synchronous setup: regular watchers declared via the watch option don't run during SSR and don't survive the render

mutating the shared state after renderToString resolves should not trigger anything

What is actually happening?

when setup() returns a Promise, the watch option creates a live watcher on the server that is never stopped

if this subscribes to state that outlives the request, it keeps the entire component instance (and app) reachable forever

System Info

Any additional comments?

_No response_

The two patches

Our patch+72 −1
packages/runtime-core/src/component.tsindex c46741bee..58e624983 100644@@ -894,7 +894,15 @@ function setupStatefulComponent(         // return the promise so server-renderer can wait on it         return setupResult           .then((resolvedResult: unknown) => {-            handleSetupResult(instance, resolvedResult, isSSR)+            // restore SSR setup state so that options API (watch, computed,+            // lifecycle hooks) applied after async setup behave as in SSR+            const prev = isInSSRComponentSetup+            setInSSRSetupState(true)+            try {+              handleSetupResult(instance, resolvedResult, isSSR)+            } finally {+              setInSSRSetupState(prev)+            }           })           .catch(e => {             handleError(e, instance, ErrorCodes.SETUP_FUNCTION)packages/server-renderer/__tests__/ssrWatch.spec.tsindex 2b1ad98d2..7714fd322 100644@@ -212,6 +212,69 @@ describe('ssr: watch', () => {     expect(beforeAwaitTriggered).toBe(false)     expect(afterAwaitTriggered).toBe(false)   })++  test('options-api watchers should not be created for async setup components', async () => {+    const open = ref(true)+    const spy = vi.fn()++    const App = defineComponent({+      setup: () => Promise.resolve({}),+      computed: {+        isOpen() {+          return open.value+        },+      },+      watch: {+        isOpen: spy,+      },+      render() {+        return h('div', String(this.isOpen))+      },+    })++    const html = await renderToString(createSSRApp(App))+    expect(html).toBe('<div>true</div>')++    // mutating the state after the request is done should not trigger the watcher+    open.value = false+    await nextTick()+    expect(spy).not.toHaveBeenCalled()+  })++  test('options-api sync / immediate watchers should be stopped after render for async setup components', async () => {+    const open = ref(true)+    const syncSpy = vi.fn()+    const immediateSpy = vi.fn()++    const App = defineComponent({+      setup: () => Promise.resolve({}),+      computed: {+        isOpen() {+          return open.value+        },+      },+      watch: {+        isOpen: [+          { handler: syncSpy, flush: 'sync' },+          { handler: immediateSpy, immediate: true },+        ],+      },+      render() {+        return h('div', String(this.isOpen))+      },+    })++    const ctx: SSRContext = {}+    const html = await renderToString(createSSRApp(App), ctx)+    expect(html).toBe('<div>true</div>')+    expect(immediateSpy).toHaveBeenCalledTimes(1)+    expect(syncSpy).not.toHaveBeenCalled()++    open.value = false+    await nextTick()+    expect(syncSpy).not.toHaveBeenCalled()+    expect(immediateSpy).toHaveBeenCalledTimes(1)+  }) })  describe('ssr: watchEffect', () => { 
Merged fix · PR #15114+75 −1
packages/runtime-core/src/component.tsindex c46741bee..162a6ad44 100644@@ -894,7 +894,12 @@ function setupStatefulComponent(         // return the promise so server-renderer can wait on it         return setupResult           .then((resolvedResult: unknown) => {-            handleSetupResult(instance, resolvedResult, isSSR)+            setInSSRSetupState(true)+            try {+              handleSetupResult(instance, resolvedResult, isSSR)+            } finally {+              setInSSRSetupState(false)+            }           })           .catch(e => {             handleError(e, instance, ErrorCodes.SETUP_FUNCTION)packages/server-renderer/__tests__/ssrWatch.spec.tsindex 2b1ad98d2..2dad83cd2 100644@@ -130,6 +130,35 @@ describe('ssr: watch', () => {     expect(msg).toBe('start')   }) +  // #15113+  test('options-api watchers should not be created for async setup components', async () => {+    const open = ref(true)+    const spy = vi.fn()++    const App = defineComponent({+      setup: () => Promise.resolve({}),+      computed: {+        isOpen() {+          return open.value+        },+      },+      watch: {+        isOpen: spy,+      },+      render() {+        return h('div', String(this.isOpen))+      },+    })++    const html = await renderToString(createSSRApp(App))+    expect(html).toBe('<div>true</div>')++    // mutating the state after the request is done should not trigger the watcher+    open.value = false+    await nextTick()+    expect(spy).not.toHaveBeenCalled()+  })+   test('should not run non-immediate watchers registered after async context restore', async () => {     const text = ref('start')     let beforeAwaitTriggered = false@@ -351,4 +380,44 @@ describe.skipIf(!global.gc)('ssr: watch gc', () => {      expect(weakRefs.filter(ref => ref.deref()).length).toBe(0)   })++  // #15113+  test('options-api should not retain apps with async setup + watcher on global state', async () => {+    const weakRefs: { deref(): unknown | undefined }[] = []++    const open = ref(true)++    const App = defineComponent({+      setup: () => Promise.resolve({}),+      computed: {+        isOpen() {+          return open.value+        },+      },+      watch: {+        isOpen() {},+      },+      render() {+        return h('div', String(this.isOpen))+      },+    })++    async function renderOnce() {+      const app = createSSRApp(App)+      // @ts-expect-error ES2021 API+      weakRefs.push(new WeakRef(app))+      const html = await renderToString(app)+      expect(html).toBe('<div>true</div>')+    }++    for (let i = 0; i < 10; i++) {+      await renderOnce()+    }++    for (let i = 0; i < 5; i++) {+      await gc()+    }++    expect(weakRefs.filter(ref => ref.deref()).length).toBe(0)+  }) })