Backtestsvuerun-20261013-093701#15091
hydrateOnVisible: Cannot read properties of null (reading 'nodeType') when the SSR node is detached before the IntersectionObserver callback fires
The merged fix was judged better than our patch.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches fix the crash in the right place, the async wrapper's `performHydrate`, by skipping hydration when the SSR node has no parent. They differ in how they handle the case where an ancestor is detached. Patch A skips whenever a hydration strategy is set and `!el.isConnected`. That is an unconditional behavior change for every strategy, including custom ones. If an app hydrates into a container that was never attached to the document (legitimate, and common in tests), a custom strategy's `hydrate()` call now silently does nothing. That is a regression risk. Patch B records `wasConnected` when `__asyncHydrate` is set up. It only skips when the node was connected then and has since been detached. This matches the issue's semantics: the node was removed before deferred hydration ran. It keeps the existing behavior for containers that were never attached. Patch A also makes `getContainerType` tolerate `null`. This is reasonable defense in depth, but it is neutral extra hardening; the guard in `performHydrate` already prevents the reported crash. On tests: - Patch A's tests are broader. They cover the connected positive case, a custom strategy, and the no-strategy loader race. - Patch B's parameterized test covers both a detached root and a detached ancestor under `hydrateOnVisible`. It fails before the fix, either by throwing on the null parent or by calling `Comp` when an ancestor is detached. Patch A's better test coverage does not outweigh the semantic risk in its `hydrateStrategy && !isConnected` condition. Patch B's fix is more precise and lower risk, with adequate tests.
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
6m 39s
Wall-clock time in the container
Full test suite
No new failures
1,735 passed · 1 skipped · 1,736 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
167vs 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..136e4b057 100644@@ -19,6 +19,7 @@ import { defineAsyncComponent, defineComponent, h,+ hydrateOnVisible, nextTick, onMounted, onServerPrefetch,@@ -1315,6 +1316,159 @@ describe('SSR hydration', () => { ) }) + describe('lazy hydration of detached SSR node', () => {+ // the resolved async component's root is itself a component, so hydrating+ // it reaches the component branch of hydrateNode, which looks up the+ // container type from the parent of the (detached) SSR node.+ const setup = () => {+ const mounted = vi.fn()+ const onClick = vi.fn()+ const Child = {+ setup() {+ onMounted(mounted)+ return () => h('button', { onClick }, 'child')+ },+ }+ const Comp = { render: () => h(Child) }+ return { mounted, onClick, Comp }+ }++ test('hydrateOnVisible: skip when node is detached before the observer callback fires', async () => {+ const { mounted, onClick, Comp } = setup()+ let observerCallback: IntersectionObserverCallback | undefined+ const observe = vi.fn()+ const disconnect = vi.fn()+ const OriginalIO = (globalThis as any).IntersectionObserver+ ;(globalThis as any).IntersectionObserver = class {+ constructor(cb: IntersectionObserverCallback) {+ observerCallback = cb+ }+ observe = observe+ disconnect = disconnect+ }++ const container = document.createElement('div')+ document.body.appendChild(container)+ try {+ const html = await renderToString(h(Comp))+ container.innerHTML = html++ const AsyncComp = defineAsyncComponent({+ loader: () => Promise.resolve(Comp),+ hydrate: hydrateOnVisible(),+ })+ createSSRApp({ render: () => h(AsyncComp) }).mount(container)+ await new Promise(r => setTimeout(r))+ expect(observe).toHaveBeenCalledTimes(1)++ // node gets detached while the intersection callback is queued+ const button = container.querySelector('button')!+ button.remove()++ expect(() =>+ observerCallback!(+ [{ isIntersecting: true } as IntersectionObserverEntry],+ {} as IntersectionObserver,+ ),+ ).not.toThrow()+ await nextTick()++ // nothing hydrated+ expect(mounted).not.toHaveBeenCalled()+ button.dispatchEvent(new Event('click'))+ expect(onClick).not.toHaveBeenCalled()+ expect(`Hydration node mismatch`).not.toHaveBeenWarned()+ } finally {+ ;(globalThis as any).IntersectionObserver = OriginalIO+ container.remove()+ }+ })++ test('hydrateOnVisible: still hydrates when node is connected', async () => {+ const { mounted, onClick, Comp } = setup()+ let observerCallback: IntersectionObserverCallback | undefined+ const OriginalIO = (globalThis as any).IntersectionObserver+ ;(globalThis as any).IntersectionObserver = class {+ constructor(cb: IntersectionObserverCallback) {+ observerCallback = cb+ }+ observe() {}+ disconnect() {}+ }++ const container = document.createElement('div')+ document.body.appendChild(container)+ try {+ container.innerHTML = await renderToString(h(Comp))+ const AsyncComp = defineAsyncComponent({+ loader: () => Promise.resolve(Comp),+ hydrate: hydrateOnVisible(),+ })+ createSSRApp({ render: () => h(AsyncComp) }).mount(container)+ await new Promise(r => setTimeout(r))++ observerCallback!(+ [{ isIntersecting: true } as IntersectionObserverEntry],+ {} as IntersectionObserver,+ )+ await nextTick()++ expect(mounted).toHaveBeenCalledTimes(1)+ container.querySelector('button')!.dispatchEvent(new Event('click'))+ expect(onClick).toHaveBeenCalledTimes(1)+ } finally {+ ;(globalThis as any).IntersectionObserver = OriginalIO+ container.remove()+ }+ })++ test('custom strategy: skip when node is detached before hydrate is triggered', async () => {+ const { mounted, Comp } = setup()+ let trigger: (() => void) | undefined+ const container = document.createElement('div')+ document.body.appendChild(container)+ try {+ container.innerHTML = await renderToString(h(Comp))+ const AsyncComp = defineAsyncComponent({+ loader: () => Promise.resolve(Comp),+ hydrate: hydrate => {+ trigger = hydrate+ },+ })+ createSSRApp({ render: () => h(AsyncComp) }).mount(container)+ await new Promise(r => setTimeout(r))++ // an ancestor is detached from the document: the node still has a+ // parent but is no longer connected+ container.remove()+ expect(() => trigger!()).not.toThrow()+ await nextTick()+ expect(mounted).not.toHaveBeenCalled()+ } finally {+ container.remove()+ }+ })++ test('no strategy: skip when node is detached before the loader resolves', async () => {+ const { mounted, Comp } = setup()+ let resolve: (comp: any) => void+ const container = document.createElement('div')+ container.innerHTML = await renderToString(h(Comp))+ const AsyncComp = defineAsyncComponent(+ () => new Promise(r => (resolve = r)),+ )+ createSSRApp({ render: () => h(AsyncComp) }).mount(container)++ // node gets detached before the async component is loaded+ container.firstChild!.remove()+ resolve!(Comp)+ await new Promise(r => setTimeout(r))++ expect(mounted).not.toHaveBeenCalled()+ expect(`Hydration node mismatch`).not.toHaveBeenWarned()+ })+ })+ test('hydrate safely when property used by async setup changed before render', async () => { const toggle = ref(true) packages/runtime-core/src/apiAsyncComponent.tsindex 66cb15a27..4f80b04fc 100644@@ -136,6 +136,14 @@ export function defineAsyncComponent< } return }+ // skip hydration if the SSR node has been detached from the DOM before+ // deferred hydration runs (e.g. removed while an IntersectionObserver+ // callback was queued) - there is nothing left to hydrate. Lazy+ // strategies operate on nodes in the document, so they additionally+ // require the node to still be connected.+ if (!el.parentNode || (hydrateStrategy && !el.isConnected)) {+ 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