Backtestsvuerun-20261005-124535#15091
hydrateOnVisible: Cannot read properties of null (reading 'nodeType') when the SSR node is detached before the IntersectionObserver callback fires
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches add a guard in `performHydrate` so a node without a parent is not hydrated. That fixes the reported crash, where `parentNode(node)` is null and `getContainerType(null)` throws. Patch A goes further in two useful ways. First, it bails when `instance.isUnmounted`, which matches the real-world trigger in the issue: a route change or re-render that unmounts the component while an observer callback is still queued. Second, it hardens `getContainerType` to accept null, which is the defense-in-depth the issue suggests. That removes the crash at its source for every caller of `getContainerType(parentNode(node))`, not just this one async path. Patch A also deliberately preserves the KeepAlive case. A deactivated KeepAlive child still has a parent in off-document storage, so A still hydrates it and it works after reactivation. Patch B's `wasConnected && !el.isConnected` check would skip hydration for that deactivated child. Because the strategy callback has already fired, the component could stay non-interactive forever after it is reactivated. That is a regression risk. B's extra coverage of the 'ancestor detached' case gives little benefit. Under A, hydrating a subtree whose ancestor is detached does not crash, since its parent is non-null. On tests, A is broader. It covers an element root, a fragment root, a nested component root (which exercises the `getContainerType` path), a custom strategy firing after unmount, the KeepAlive positive case, and the normal connected case, and it asserts that event handlers are not attached. B tests only root and ancestor detachment with `hydrateOnVisible`. Overall, A is more correct, safer around KeepAlive, and better tested.
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
11m 32s
Wall-clock time in the container
Full test suite
No new failures
3,624 passed · 6 skipped · 3,630 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
187vs 56 merged
Changed lines, ours vs merged
The issue
View on GitHubVue version
3.5.33
Link to minimal reproduction
https://stackblitz.com/edit/vitejs-vite-ktsycrrc?file=repro.mjs
Steps to reproduce
- SSR-render an async component that uses hydrate: hydrateOnVisible().
- On the client, hydration is deferred and the strategy registers an IntersectionObserver on the component's SSR node.
- 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).
- 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
packages/runtime-core/__tests__/hydration.spec.tsindex df0114065..f3ee6267c 100644@@ -19,6 +19,7 @@ import { defineAsyncComponent, defineComponent, h,+ hydrateOnVisible, nextTick, onMounted, onServerPrefetch,@@ -1315,6 +1316,177 @@ describe('SSR hydration', () => { ) }) + describe('lazy hydration with detached SSR node', () => {+ const OriginalIntersectionObserver = (window as any).IntersectionObserver+ let observerCallbacks: IntersectionObserverCallback[]++ beforeEach(() => {+ observerCallbacks = []+ ;(window as any).IntersectionObserver = class {+ constructor(cb: IntersectionObserverCallback) {+ observerCallbacks.push(cb)+ }+ observe() {}+ disconnect() {}+ }+ })++ afterEach(() => {+ ;(window as any).IntersectionObserver = OriginalIntersectionObserver+ document.body.innerHTML = ''+ })++ const fireIntersection = () => {+ observerCallbacks.forEach(cb =>+ cb([{ isIntersecting: true } as IntersectionObserverEntry], {} as any),+ )+ }++ async function setup(+ Comp: any,+ hydrate: any,+ render: (AsyncComp: any) => any = AsyncComp => h(AsyncComp),+ ) {+ const mounted = vi.fn()+ const Inner = { ...Comp, mounted }+ // separate definitions for server & client so that the client one is+ // still unresolved at hydration time, as in a real app+ const createApp = () => {+ const AsyncComp = defineAsyncComponent({+ loader: () => Promise.resolve(Inner),+ hydrate,+ })+ return { render: () => render(AsyncComp) }+ }+ const html = await renderToString(h(createApp()))+ const container = document.createElement('div')+ container.innerHTML = html+ document.body.appendChild(container)+ const app = createSSRApp(createApp())+ app.mount(container)+ // wait for the loader to resolve so the strategy gets registered+ await new Promise(r => setTimeout(r))+ return { container, app, mounted }+ }++ test('hydrateOnVisible: skip hydration when element root is detached', async () => {+ const handler = vi.fn()+ const { container, mounted } = await setup(+ {+ render: () => h('div', { onClick: handler }, 'below the fold'),+ },+ hydrateOnVisible(),+ )+ expect(observerCallbacks.length).toBe(1)+ const el = container.firstChild as HTMLElement+ // detach the SSR node before the queued observer callback runs+ container.removeChild(el)++ expect(() => fireIntersection()).not.toThrow()+ await nextTick()+ expect(mounted).not.toHaveBeenCalled()+ el.dispatchEvent(new Event('click'))+ expect(handler).not.toHaveBeenCalled()+ })++ test('hydrateOnVisible: skip hydration when fragment root is detached', async () => {+ const { container, mounted } = await setup(+ {+ render: () => [h('div', 'a'), h('div', 'b')],+ },+ hydrateOnVisible(),+ )+ expect(observerCallbacks.length).toBe(1)+ // detach the entire SSR fragment (including its anchors)+ while (container.firstChild) container.removeChild(container.firstChild)++ expect(() => fireIntersection()).not.toThrow()+ await nextTick()+ expect(mounted).not.toHaveBeenCalled()+ })++ test('hydrateOnVisible: skip hydration when nested component root is detached', async () => {+ // the inner component's root is itself a component, so hydration calls+ // getContainerType(parentNode(node)) on the detached node+ const Child = { render: () => h('span', 'child') }+ const { container, mounted } = await setup(+ { render: () => h(Child) },+ hydrateOnVisible(),+ )+ container.removeChild(container.firstChild!)++ expect(() => fireIntersection()).not.toThrow()+ await nextTick()+ expect(mounted).not.toHaveBeenCalled()+ })++ test('custom strategy: skip hydration when invoked after the component was unmounted', async () => {+ let doHydrate!: () => void+ const show = ref(true)+ const { container, mounted } = await setup(+ { render: () => h('div', 'lazy') },+ (hydrate: () => void) => {+ doHydrate = hydrate+ // intentionally no teardown: simulates a callback already queued+ },+ AsyncComp => (show.value ? h(AsyncComp) : h('p', 'off')),+ )+ show.value = false+ await nextTick()+ expect(container.innerHTML).toBe('<p>off</p>')++ expect(() => doHydrate()).not.toThrow()+ await nextTick()+ expect(mounted).not.toHaveBeenCalled()+ expect(container.innerHTML).toBe('<p>off</p>')+ })++ test('custom strategy: still hydrates when deactivated by KeepAlive', async () => {+ let doHydrate!: () => void+ const show = ref(true)+ const handler = vi.fn()+ const { container, mounted } = await setup(+ { render: () => h('div', { onClick: handler }, 'lazy') },+ (hydrate: () => void) => {+ doHydrate = hydrate+ },+ AsyncComp =>+ h(runtimeDom.KeepAlive, null, {+ default: () => (show.value ? h(AsyncComp) : h('p', 'off')),+ }),+ )+ // deactivate: the SSR node is moved into KeepAlive's off-document storage+ show.value = false+ await nextTick()+ expect(container.innerHTML).toBe('<p>off</p>')++ expect(() => doHydrate()).not.toThrow()+ await nextTick()+ expect(mounted).toHaveBeenCalledTimes(1)++ show.value = true+ await nextTick()+ expect(container.innerHTML).toBe('<div>lazy</div>')+ container.firstChild!.dispatchEvent(new Event('click'))+ expect(handler).toHaveBeenCalledTimes(1)+ })++ test('hydrateOnVisible: still hydrates when node stays connected', async () => {+ const handler = vi.fn()+ const { container, mounted } = await setup(+ {+ render: () => h('div', { onClick: handler }, 'below the fold'),+ },+ hydrateOnVisible(),+ )+ fireIntersection()+ await nextTick()+ expect(mounted).toHaveBeenCalledTimes(1)+ container.firstChild!.dispatchEvent(new Event('click'))+ expect(handler).toHaveBeenCalledTimes(1)+ })+ })+ test('hydrate safely when property used by async setup changed before render', async () => { const toggle = ref(true) packages/runtime-core/src/apiAsyncComponent.tsindex 66cb15a27..20dd10355 100644@@ -136,6 +136,14 @@ export function defineAsyncComponent< } return }+ // skip hydration if the component has been unmounted, or its SSR node+ // has been detached (e.g. a queued strategy callback such as+ // IntersectionObserver fires after a route change / re-render)+ // - there is nothing left to hydrate. Note: a node moved into+ // KeepAlive's off-document storage still has a parent and is hydrated.+ if (instance.isUnmounted || !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,
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