Backtestsvuerun-20261005-155915#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 stop the reported crash by bailing in `performHydrate` when `el.parentNode` is null, so `getContainerType(null)` is never reached. Patch A is the better fix for three reasons. 1. **It guards on unmount state.** It adds `instance.isUnmounted`, which covers the real-world route-change scenario. In that case Vue unmounts the component, possibly by removing an ancestor rather than the node itself, so the node can still have a parent. 2. **It adds defense-in-depth.** It hardens `getContainerType` to tolerate a null container, as the issue suggests. That function is called with `parentNode(node)` at several sites. 3. **It preserves KeepAlive behavior, and B breaks it.** When a KeepAlive deactivates a component, the node moves into off-document storage but stays parented. A still hydrates it, and has a test proving the component is interactive after reactivation. B uses `wasConnected && !el.isConnected`, so it skips hydration in exactly that case. The observer has already fired, so the component could stay permanently non-interactive after reactivation. That is a regression risk. On tests, A is more thorough. It covers: - the detached-node case - the KeepAlive case - the unmounted-but-still-parented case - the normal attached hydration path, as a non-regression check - the no-strategy loader-resolves-after-removal case Its tests also check the observable outcome: `onMounted` is not called and click handlers are not attached. B's tests cover root and ancestor detachment only, assert just that the render function isn't called, and use a cruder setup. Overall, A is more correct, safer 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
10m 9s
Wall-clock time in the container
Full test suite
No new failures
3,622 passed · 6 skipped · 3,629 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
197vs 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..2a4df9887 100644@@ -3,6 +3,8 @@ */ import {+ type HydrationStrategy,+ KeepAlive, type ObjectDirective, Suspense, Teleport,@@ -19,6 +21,7 @@ import { defineAsyncComponent, defineComponent, h,+ hydrateOnVisible, nextTick, onMounted, onServerPrefetch,@@ -1191,6 +1194,187 @@ describe('SSR hydration', () => { expect(spy).toHaveBeenCalled() }) + describe('lazy hydration of a detached SSR node', () => {+ const OriginalIO = (globalThis as any).IntersectionObserver+ let observerCallback: IntersectionObserverCallback | undefined+ let observed: Element[] = []++ beforeEach(() => {+ observerCallback = undefined+ observed = []+ ;(globalThis as any).IntersectionObserver = class {+ constructor(cb: IntersectionObserverCallback) {+ observerCallback = cb+ }+ observe(el: Element) {+ observed.push(el)+ }+ disconnect() {}+ }+ })++ afterEach(() => {+ ;(globalThis as any).IntersectionObserver = OriginalIO+ document.body.innerHTML = ''+ })++ const fireIntersection = () => {+ const entries = observed.map(target => ({ isIntersecting: true, target }))+ observerCallback!(entries as any, {} as IntersectionObserver)+ }++ const setup = async (options: { hydrate?: HydrationStrategy }) => {+ const mountedSpy = vi.fn()+ const clickSpy = vi.fn()+ const Comp = {+ setup() {+ onMounted(mountedSpy)+ return () => h('button', { onClick: clickSpy }, 'hello')+ },+ }+ const html = await renderToString(+ h(defineAsyncComponent(() => Promise.resolve(Comp))),+ )+ expect(html).toBe('<button>hello</button>')++ let clientResolve!: (c: any) => void+ const AsyncComp = defineAsyncComponent({+ loader: () => new Promise<any>(r => (clientResolve = r)),+ ...options,+ })+ const container = document.createElement('div')+ container.innerHTML = html+ document.body.appendChild(container)+ const app = createSSRApp({ render: () => h(AsyncComp) })+ app.mount(container)+ const button = container.querySelector('button')!+ return {+ app,+ container,+ button,+ mountedSpy,+ clickSpy,+ Comp,+ clientResolve,+ }+ }++ test('hydrateOnVisible: node removed before observer callback fires', async () => {+ const { button, mountedSpy, clickSpy, Comp, clientResolve } =+ await setup({ hydrate: hydrateOnVisible() })+ clientResolve(Comp)+ await new Promise(r => setTimeout(r))+ expect(observed).toEqual([button])++ // node is detached (e.g. route change) while the callback is queued+ button.remove()+ expect(() => fireIntersection()).not.toThrow()+ await nextTick()++ expect(mountedSpy).not.toHaveBeenCalled()+ triggerEvent('click', button)+ expect(clickSpy).not.toHaveBeenCalled()+ })++ test('hydrateOnVisible: still hydrates when deactivated by KeepAlive before observer callback fires', async () => {+ const mountedSpy = vi.fn()+ const clickSpy = vi.fn()+ const Comp = {+ setup() {+ onMounted(mountedSpy)+ return () => h('button', { onClick: clickSpy }, 'hello')+ },+ }+ const makeApp = (AsyncComp: any) => {+ const Wrapper = { render: () => h('div', [h(AsyncComp)]) }+ const show = ref(true)+ const app = createSSRApp({+ render: () =>+ h(KeepAlive, null, [show.value ? h(Wrapper) : h('span', 'other')]),+ })+ return { app, show }+ }+ const html = await renderToString(+ makeApp(defineAsyncComponent(() => Promise.resolve(Comp))).app,+ )++ let clientResolve!: (c: any) => void+ const { app, show } = makeApp(+ defineAsyncComponent({+ loader: () => new Promise<any>(r => (clientResolve = r)),+ hydrate: hydrateOnVisible(),+ }),+ )+ const container = document.createElement('div')+ container.innerHTML = html+ document.body.appendChild(container)+ app.mount(container)+ const button = container.querySelector('button')!+ clientResolve(Comp)+ await new Promise(r => setTimeout(r))+ expect(observed).toEqual([button])++ // deactivate: the SSR node is moved off-document into KeepAlive storage+ show.value = false+ await nextTick()+ expect(button.isConnected).toBe(false)+ expect(() => fireIntersection()).not.toThrow()+ await nextTick()+ expect(mountedSpy).toHaveBeenCalledTimes(1)++ // reactivate: the hydrated component is interactive+ show.value = true+ await nextTick()+ expect(button.isConnected).toBe(true)+ triggerEvent('click', button)+ expect(clickSpy).toHaveBeenCalledTimes(1)+ })++ test('hydrateOnVisible: component unmounted before observer callback fires', async () => {+ const { app, container, button, mountedSpy, Comp, clientResolve } =+ await setup({ hydrate: hydrateOnVisible() })+ clientResolve(Comp)+ await new Promise(r => setTimeout(r))+ expect(observed).toEqual([button])++ // keep the node parented so only the unmount state can prevent hydration+ app.unmount()+ container.appendChild(button)+ expect(() => fireIntersection()).not.toThrow()+ await nextTick()++ expect(mountedSpy).not.toHaveBeenCalled()+ })++ test('hydrateOnVisible: still hydrates when node stays attached', async () => {+ const { button, mountedSpy, clickSpy, Comp, clientResolve } =+ await setup({ hydrate: hydrateOnVisible() })+ clientResolve(Comp)+ await new Promise(r => setTimeout(r))++ fireIntersection()+ await nextTick()++ expect(mountedSpy).toHaveBeenCalledTimes(1)+ triggerEvent('click', button)+ expect(clickSpy).toHaveBeenCalledTimes(1)+ })++ test('no strategy: node removed before async loader resolves', async () => {+ const { button, mountedSpy, clickSpy, Comp, clientResolve } =+ await setup({})++ button.remove()+ clientResolve(Comp)+ // a throw here would surface as an unhandled rejection+ await new Promise(r => setTimeout(r))++ expect(mountedSpy).not.toHaveBeenCalled()+ triggerEvent('click', button)+ expect(clickSpy).not.toHaveBeenCalled()+ })+ })+ test('update async wrapper before resolve', async () => { const Comp = { render() {packages/runtime-core/src/apiAsyncComponent.tsindex 66cb15a27..377e0cf23 100644@@ -136,6 +136,14 @@ export function defineAsyncComponent< } return }+ // skip hydration if the component has been unmounted or its SSR node+ // has been removed in the meantime (e.g. by a route change before the+ // strategy fired) - there is nothing left to hydrate. A node that is+ // only off-document but still parented (e.g. moved into KeepAlive's+ // storage container) is still hydrated.+ if (instance.isUnmounted || !el.parentNode) {+ return+ } hydrate() } const doHydrate = hydrateStrategypackages/runtime-core/src/hydration.tsindex 405a5db93..672b7d3c1 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
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