Backtestsvuerun-20261003-231210#15091

Issue #15091 Merged fix PR #15092 Run 3 Oct 2026 · run-20261003-231210 vuejs/core

hydrateOnVisible: Cannot read properties of null (reading 'nodeType') when the SSR node is detached before the IntersectionObserver callback fires

Better

Our patch was judged better than the merged fix.

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

Both patches put the same guard in `__asyncHydrate`'s `performHydrate`: record `wasConnected` when hydration is scheduled, then bail if `!el.parentNode || (wasConnected && !el.isConnected)`. So both fix the root cause the issue identifies, and they behave identically for the reported scenario (node detached, or an ancestor detached, before the IntersectionObserver callback fires).

Differences:

1. Defense-in-depth. B also makes `getContainerType` accept a `null` container and drops the non-null assertion at the async-component call site. The issue explicitly suggests this hardening. It is small and low-risk, and it protects other paths where `parentNode(node)` could be null. On its own this is neutral, but it does not obscure the fix.

2. Tests. A tests `hydrateOnVisible` with two cases: the root detached and an ancestor detached. The ancestor case is the one that exercises the `wasConnected && !isConnected` branch, which is a nice touch.

   B's tests are broader:
   - `hydrateOnVisible`, checking that the observer was attached to the right element.
   - `hydrateOnIdle`.
   - The no-strategy path, where the node is detached before load resolves.
   - A custom strategy whose container was never in the document. This verifies that the `!el.parentNode` / `wasConnected` logic handles the disconnected-from-start case correctly.
   - A positive control confirming that hydration still happens when the node stays connected, guarding against over-eager bailing.

   B lacks an explicit ancestor-detach case. However, its coverage of multiple strategies plus the regression-safety positive test is more valuable overall.

3. Craft. B's comments explain the intent of the `wasConnected` capture, which is a non-obvious condition. A's terse version leaves the reader to infer why `wasConnected` matters.

Core correctness is equal. B wins on test breadth (including the positive control), the issue-suggested hardening, and clarity.

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

8m 47s

Wall-clock time in the container

Full test suite

No new failures

3,623 passed · 6 skipped · 3,629 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

139vs 56 merged

Changed lines, ours vs merged

Vue version

3.5.33

Link to minimal reproduction

https://stackblitz.com/edit/vitejs-vite-ktsycrrc?file=repro.mjs

Steps to reproduce

  1. SSR-render an async component that uses hydrate: hydrateOnVisible().
  2. On the client, hydration is deferred and the strategy registers an IntersectionObserver on the component's SSR node.
  3. The node gets detached from the document before the observer's callback executes (in production this is a route change / re-render while the intersection callback is already queued).
  4. The observer callback runs and invokes hydrate() against the now-detached node.

What is expected?

A node that is no longer connected to the document should simply not be hydrated (there's nothing to hydrate), no exception thrown.

What is actually happening?

hydrate() reaches hydrateNode, which computes the container type from the node's parent:

// packages/runtime-core/src/hydration.ts — inside hydrateNode, async-component branch
nextNode = vnode.type.hydrate(
  node, vnode, parentComponent, parentSuspense,
  getContainerType(parentNode(node)),   // parentNode(node) === null for a detached node
  slotScopeIds, optimized, rendererInternals, hydrateNode,
)
// packages/runtime-core/src/hydration.ts
const getContainerType = (container) => {
  if (container.nodeType !== 1) return undefined   // <-- container is null -> throws
  ...
}

For a detached node parentNode(node) is null, so getContainerType(null) throws TypeError: Cannot read properties of null (reading 'nodeType').

The async-component hydration wrapper only guards against the patched case, never against disconnection:

// packages/runtime-core/src/apiAsyncComponent.ts — __asyncHydrate
const performHydrate = () => {
  if (patched) { /* warn + */ return }   // only guards `patched`
  hydrate()                              // no isConnected check
}

Because the strategy runs inside load().then(...), the throw surfaces as an unhandledrejection, so app-level try/catch around the component can't catch it.

System Info

vue: 3.5.33
@vue/server-renderer: 3.5.33
Environment where it triggers: Android WebView (Chrome), production SSR + client hydration

Any additional comments?

We see this almost exclusively on Android Chrome WebView (~43k occurrences / ~12.8k users over a rollout window) on a page that lazy-hydrates several below-the-fold sections via hydrateOnVisible. The IntersectionObserver callback is dispatched asynchronously; when the user navigates/re-renders in the WebView, the observed node is detached between the intersection being recorded and the callback running, exactly the sequence above. Desktop rarely hits the race.

Skip hydration when the anchor node is no longer connected. the semantically correct place is the async performHydrate (or each built-in strategy's trigger), e.g. bail when no observed/anchor element isConnected:

const performHydrate = () => {
  if (patched) { return }
  if (el && !el.isConnected) return   // detached before hydration → nothing to hydrate
  hydrate()
}

As defense-in-depth, getContainerType could also tolerate a null container (if (!container || container.nodeType !== 1) return undefined), since it's called with parentNode(node) at several sites.

We're currently shipping a userland wrapper around hydrateOnVisible that applies exactly the isConnected guard, which fully stops the crash.

The two patches

Our patch+136 −3
packages/runtime-core/__tests__/hydration.spec.tsindex df0114065..2b22eefa3 100644@@ -3,6 +3,7 @@  */  import {+  type HydrationStrategy,   type ObjectDirective,   Suspense,   Teleport,@@ -19,6 +20,8 @@ import {   defineAsyncComponent,   defineComponent,   h,+  hydrateOnIdle,+  hydrateOnVisible,   nextTick,   onMounted,   onServerPrefetch,@@ -1456,6 +1459,125 @@ describe('SSR hydration', () => {     )   }) +  // #15091+  describe('lazy hydration of a node detached before hydration', () => {+    const createLazyComp = (+      hydrate: HydrationStrategy | undefined,+      loader?: () => Promise<any>,+    ) => {+      const mounted = vi.fn()+      const Comp = defineComponent({+        setup() {+          onMounted(mounted)+          return () => h('button', 'lazy')+        },+      })+      const AsyncComp = defineAsyncComponent({+        loader: loader || (() => Promise.resolve(Comp)),+        hydrate,+      })+      return { AsyncComp, Comp, mounted }+    }++    const mountAttached = (AsyncComp: any) => {+      const container = document.createElement('div')+      container.innerHTML = '<div><button>lazy</button></div>'+      document.body.appendChild(container)+      createSSRApp({+        render: () => h('div', [h(AsyncComp)]),+      }).mount(container)+      return container+    }++    test('hydrateOnVisible', async () => {+      let callback: IntersectionObserverCallback | undefined+      const observe = vi.fn()+      class MockIntersectionObserver {+        constructor(cb: IntersectionObserverCallback) {+          callback = cb+        }+        observe = observe+        disconnect() {}+      }+      vi.stubGlobal('IntersectionObserver', MockIntersectionObserver)+      try {+        const { AsyncComp, mounted } = createLazyComp(hydrateOnVisible())+        const container = mountAttached(AsyncComp)+        await new Promise(r => setTimeout(r))++        const button = container.querySelector('button')!+        expect(observe).toHaveBeenCalledWith(button)++        // node is detached while the intersection callback is still queued+        button.remove()+        expect(() =>+          callback!(+            [{ isIntersecting: true } as IntersectionObserverEntry],+            {} as IntersectionObserver,+          ),+        ).not.toThrow()+        await nextTick()+        expect(mounted).not.toHaveBeenCalled()+        container.remove()+      } finally {+        vi.unstubAllGlobals()+      }+    })++    test('hydrateOnIdle', async () => {+      const { AsyncComp, mounted } = createLazyComp(hydrateOnIdle())+      const container = mountAttached(AsyncComp)+      // detach before the idle callback fires+      container.querySelector('button')!.remove()+      await new Promise(r => setTimeout(r, 10))+      expect(mounted).not.toHaveBeenCalled()+      expect(container.innerHTML).toBe('<div></div>')+      container.remove()+    })++    test('without hydration strategy (detached before load)', async () => {+      let resolve: (comp: any) => void+      const { AsyncComp, Comp, mounted } = createLazyComp(+        undefined,+        () => new Promise(r => (resolve = r)),+      )+      const container = mountAttached(AsyncComp)+      container.querySelector('button')!.remove()+      resolve!(Comp)+      await new Promise(r => setTimeout(r))+      expect(mounted).not.toHaveBeenCalled()+      expect(container.innerHTML).toBe('<div></div>')+      container.remove()+    })++    test('custom strategy, container not in the document', async () => {+      let doHydrate: (() => void) | undefined+      const { AsyncComp, mounted } = createLazyComp(hydrate => {+        doHydrate = hydrate+      })+      const container = document.createElement('div')+      container.innerHTML = '<div><button>lazy</button></div>'+      createSSRApp({+        render: () => h('div', [h(AsyncComp)]),+      }).mount(container)+      await new Promise(r => setTimeout(r))++      container.querySelector('button')!.remove()+      expect(() => doHydrate!()).not.toThrow()+      await nextTick()+      expect(mounted).not.toHaveBeenCalled()+      expect(container.innerHTML).toBe('<div></div>')+    })++    test('still hydrates when the node stays connected', async () => {+      const { AsyncComp, mounted } = createLazyComp(hydrateOnIdle())+      const container = mountAttached(AsyncComp)+      await new Promise(r => setTimeout(r, 10))+      expect(mounted).toHaveBeenCalledTimes(1)+      container.remove()+    })+  })+   // #3787   test('unmount async wrapper before load', async () => {     let resolve: anypackages/runtime-core/src/apiAsyncComponent.tsindex 66cb15a27..2eb1f36b1 100644@@ -124,6 +124,10 @@ export function defineAsyncComponent<      __asyncHydrate(el, instance, hydrate) {       let patched = false+      // record whether the SSR node is attached to the document at the time+      // hydration is scheduled, so that a node detached before the deferred+      // hydration fires can be detected (#15091)+      const wasConnected = el.isConnected       ;(instance.bu || (instance.bu = [])).push(() => (patched = true))       const performHydrate = () => {         // skip hydration if the component has been patched@@ -136,6 +140,12 @@ export function defineAsyncComponent<           }           return         }+        // skip hydration if the node has been detached (from the document or+        // from its parent) before the (deferred) hydration was performed -+        // there is nothing left to hydrate.+        if ((wasConnected && !el.isConnected) || !el.parentNode) {+          return+        }         hydrate()       }       const doHydrate = hydrateStrategypackages/runtime-core/src/hydration.tsindex 405a5db93..a23c52486 100644@@ -73,9 +73,10 @@ const isMathMLContainer = (container: Element) =>   container.namespaceURI!.includes('MathML')  const getContainerType = (-  container: Element | ShadowRoot,+  container: Element | ShadowRoot | null, ): 'svg' | 'mathml' | undefined => {-  if (container.nodeType !== DOMNodeTypes.ELEMENT) return undefined+  if (!container || container.nodeType !== DOMNodeTypes.ELEMENT)+    return undefined   if (isSVGContainer(container as Element)) return 'svg'   if (isMathMLContainer(container as Element)) return 'mathml'   return undefined@@ -347,7 +348,7 @@ export function createHydrationFunctions(             vnode,             parentComponent,             parentSuspense,-            getContainerType(parentNode(node)!),+            getContainerType(parentNode(node)),             slotScopeIds,             optimized,             rendererInternals, 
Merged fix · PR #15092+56 −0
packages/runtime-core/__tests__/hydration.spec.tsindex df0114065..89fa5e829 100644@@ -19,6 +19,7 @@ import {   defineAsyncComponent,   defineComponent,   h,+  hydrateOnVisible,   nextTick,   onMounted,   onServerPrefetch,@@ -1191,6 +1192,59 @@ describe('SSR hydration', () => {     expect(spy).toHaveBeenCalled()   }) +  // #15091+  async function assertSkipLazyHydration(detached: 'root' | 'ancestor') {+    let observer!: IntersectionObserver+    let observerCallback!: IntersectionObserverCallback+    const originalIntersectionObserver = globalThis.IntersectionObserver+    globalThis.IntersectionObserver = class {+      constructor(callback: IntersectionObserverCallback) {+        observer = this as any+        observerCallback = callback+      }+      disconnect() {}+      observe() {}+    } as any++    try {+      const Comp = vi.fn(() => h('p', 'hello'))+      const AsyncComp = defineAsyncComponent({+        loader: () => Promise.resolve(Comp),+        hydrate: hydrateOnVisible(),+      })+      const App = () => h(AsyncComp)+      const container = document.createElement('div')++      container.innerHTML = await renderToString(h(App))+      document.body.appendChild(container)+      Comp.mockClear()+      createSSRApp(App).mount(container)++      const el = container.firstElementChild!+      if (detached === 'root') {+        el.remove()+      } else {+        container.remove()+      }+      expect(el.isConnected).toBe(false)++      expect(() =>+        observerCallback(+          [{ isIntersecting: true, target: el } as IntersectionObserverEntry],+          observer,+        ),+      ).not.toThrow()+      expect(Comp).not.toHaveBeenCalled()+    } finally {+      globalThis.IntersectionObserver = originalIntersectionObserver+    }+  }++  test.each(['root', 'ancestor'] as const)(+    'skip lazy hydration when the SSR %s is detached',+    assertSkipLazyHydration,+  )+   test('update async wrapper before resolve', async () => {     const Comp = {       render() {packages/runtime-core/src/apiAsyncComponent.tsindex 66cb15a27..95de65b8e 100644@@ -123,6 +123,7 @@ export function defineAsyncComponent<     __asyncLoader: load,      __asyncHydrate(el, instance, hydrate) {+      const wasConnected = el.isConnected       let patched = false       ;(instance.bu || (instance.bu = [])).push(() => (patched = true))       const performHydrate = () => {@@ -136,6 +137,7 @@ export function defineAsyncComponent<           }           return         }+        if (!el.parentNode || (wasConnected && !el.isConnected)) return         hydrate()       }       const doHydrate = hydrateStrategy