Backtestsvuerun-20261007-145226#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 add a guard in `__asyncHydrate`'s `performHydrate`, which is where the issue says the fix belongs. They differ on what counts as 'detached'. Patch A bails only when `!el.parentNode`. That stops the reported crash when the SSR root node itself is removed. It does not cover the case where an ancestor is removed. There, `el.parentNode` is still set, so A goes ahead and hydrates a subtree that is no longer in the document: mount hooks run and listeners attach to orphaned DOM. The issue explicitly asks that a node no longer connected to the document not be hydrated, and its suggested fix uses `isConnected`. A also adds a null guard in `getContainerType`. That is reasonable defense-in-depth but earns no credit on its own. Patch B bails on `!el.parentNode || (wasConnected && !el.isConnected)`. That handles both direct removal and ancestor removal, matching the issue's `isConnected` semantics. Capturing `wasConnected` at setup time keeps existing behavior when hydrating into a container that was never attached to the document, as in many tests, so it should not regress current suites. This is a careful edge-case consideration. Tests: both add tests that would fail before the change. - A covers single-root, fragment and component roots, plus a positive 'still hydrates' case, but only with direct detachment. - B parameterizes over root versus ancestor detachment. Its ancestor test exercises exactly the gap in A's logic. A's positive test is a nice addition, but B's guard is more faithful to the issue's intent and more robust in the real-world scenario (route change or re-render detaching a parent). On correctness, which weighs most, B wins.
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 16s
Wall-clock time in the container
Full test suite
No new failures
3,622 passed · 6 skipped · 3,628 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
131vs 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..aa03b04a7 100644@@ -19,6 +19,7 @@ import { defineAsyncComponent, defineComponent, h,+ hydrateOnVisible, nextTick, onMounted, onServerPrefetch,@@ -1315,6 +1316,124 @@ describe('SSR hydration', () => { ) }) + describe('lazy hydration of a detached SSR node', () => {+ let observerCallbacks: IntersectionObserverCallback[] = []+ const OriginalIntersectionObserver = (globalThis as any)+ .IntersectionObserver++ beforeEach(() => {+ observerCallbacks = []+ ;(globalThis as any).IntersectionObserver = class {+ constructor(cb: IntersectionObserverCallback) {+ observerCallbacks.push(cb)+ }+ observe() {}+ disconnect() {}+ }+ })++ afterEach(() => {+ ;(globalThis as any).IntersectionObserver = OriginalIntersectionObserver+ })++ const triggerIntersection = () => {+ for (const cb of observerCallbacks) {+ cb([{ isIntersecting: true } as IntersectionObserverEntry], {} as any)+ }+ }++ async function setup(Comp: any) {+ const AsyncComp = defineAsyncComponent({+ loader: () => Promise.resolve(Comp),+ hydrate: hydrateOnVisible(),+ })+ const App = { render: () => h('div', [h(AsyncComp)]) }+ const html = await renderToString(h(App))++ const container = document.createElement('div')+ container.innerHTML = html+ createSSRApp(App).mount(container)+ // wait for the async loader to resolve and the strategy to be set up+ await new Promise(r => setTimeout(r))+ expect(observerCallbacks.length).toBe(1)+ return container+ }++ // detached between the intersection being recorded and the callback running+ test('single root', async () => {+ const spy = vi.fn()+ const mountedSpy = vi.fn()+ const Comp = {+ setup() {+ onMounted(mountedSpy)+ return () => h('button', { onClick: spy }, 'click')+ },+ }+ const container = await setup(Comp)+ const button = container.querySelector('button')!+ button.remove()++ expect(() => triggerIntersection()).not.toThrow()+ expect(mountedSpy).not.toHaveBeenCalled()+ button.dispatchEvent(new Event('click'))+ expect(spy).not.toHaveBeenCalled()+ expect(`Hydration node mismatch`).not.toHaveBeenWarned()+ })++ test('fragment root', async () => {+ const spy = vi.fn()+ const mountedSpy = vi.fn()+ const Comp = {+ setup() {+ onMounted(mountedSpy)+ return () => [+ h('button', { onClick: spy }, 'click'),+ h('span', 'foo'),+ ]+ },+ }+ const container = await setup(Comp)+ const button = container.querySelector('button')!+ // detach the whole fragment, including its anchors+ const wrapper = container.firstChild!+ while (wrapper.firstChild) wrapper.removeChild(wrapper.firstChild)++ expect(() => triggerIntersection()).not.toThrow()+ expect(mountedSpy).not.toHaveBeenCalled()+ button.dispatchEvent(new Event('click'))+ expect(spy).not.toHaveBeenCalled()+ })++ test('component root', async () => {+ const spy = vi.fn()+ const mountedSpy = vi.fn()+ const Child = {+ setup() {+ onMounted(mountedSpy)+ return () => h('button', { onClick: spy }, 'click')+ },+ }+ const Comp = { render: () => h(Child) }+ const container = await setup(Comp)+ const button = container.querySelector('button')!+ button.remove()++ expect(() => triggerIntersection()).not.toThrow()+ expect(mountedSpy).not.toHaveBeenCalled()+ button.dispatchEvent(new Event('click'))+ expect(spy).not.toHaveBeenCalled()+ })++ test('still hydrates when the node remains attached', async () => {+ const spy = vi.fn()+ const Comp = () => h('button', { onClick: spy }, 'click')+ const container = await setup(Comp)+ triggerIntersection()+ container.querySelector('button')!.dispatchEvent(new Event('click'))+ expect(spy).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..3c055c9bd 100644@@ -136,6 +136,13 @@ export function defineAsyncComponent< } return }+ // skip hydration if the SSR node has been detached from its parent+ // before the (possibly deferred) hydration strategy triggered, e.g. an+ // IntersectionObserver callback that was already queued when the node+ // got removed. There is nothing left to hydrate in that case.+ if (!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