Backtestsvuerun-20261021-133314#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 at the real trigger: the async wrapper's performHydrate now bails when the SSR node has no parent, so getContainerType(parentNode(node)) is never reached with null. Both pass the two independent tests that reproduce the issue's actual scenarios (node removed from its parent; app unmounted while the observer callback is queued). The one divergence is the third independent test: when only an ancestor is detached, B skips hydration and A hydrates the still-parented subtree. That matches the issue's 'should not be hydrated' wording, but it is not the crash, and A's choice is deliberate and defensible: A ships a test showing that a subtree temporarily detached (e.g. moved into KeepAlive's storage container) and re-attached still becomes interactive. Under B, that scenario is a regression: hydrateOnVisible calls ob.disconnect() before hydrate(), and hydrateOnIdle has no retry, so a component whose subtree happened to be detached when the trigger fired is skipped permanently and never hydrates after re-attachment. B's wasConnected heuristic only protects the never-connected (test container) case, not temporary detachment. A also adds the defense-in-depth the issue asked for (getContainerType tolerates null, the non-null assertion at the call site is removed), guards instance.isUnmounted explicitly, and brings a much broader test suite: strategy skip, unmount, re-attach, still-attached, a real hydrateOnVisible mock, and the no-strategy path asserting no unhandledRejection. B's tests are adequate but narrower. On correctness A is safer (never throws, never strands a component), on tests A is stronger, and its extra scope is low-risk and issue-requested.
Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.
Solve
8m 42s
Wall-clock time in the container
Full test suite
No new failures
1,737 passed · 1 skipped · 1,738 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
182vs 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..3b23882fb 100644@@ -19,6 +19,7 @@ import { defineAsyncComponent, defineComponent, h,+ hydrateOnVisible, nextTick, onMounted, onServerPrefetch,@@ -1315,6 +1316,173 @@ describe('SSR hydration', () => { ) }) + describe('lazy hydration of detached SSR node', () => {+ const Comp = {+ setup() {+ const count = ref(0)+ return () =>+ h('button', { onClick: () => count.value++ }, String(count.value))+ },+ }++ async function setup(+ hydrateStrategy: any,+ clientLoader: () => Promise<any> = () => Promise.resolve(Comp),+ parent?: Element,+ ) {+ const App = {+ props: ['comp'],+ render(this: any) {+ return h('div', [h(this.comp)])+ },+ }+ const html = await renderToString(+ h(App, { comp: defineAsyncComponent(() => Promise.resolve(Comp)) }),+ )+ expect(html).toBe('<div><button>0</button></div>')++ const container = document.createElement('div')+ container.innerHTML = html+ if (parent) parent.appendChild(container)+ const AsyncComp = defineAsyncComponent({+ loader: clientLoader,+ hydrate: hydrateStrategy,+ })+ const app = createSSRApp(App, { comp: AsyncComp })+ app.mount(container)+ return Object.assign(container, { app })+ }++ afterEach(() => {+ document.body.innerHTML = ''+ })++ test('skip hydration when node removed from its parent', async () => {+ let doHydrate: () => void+ const container = await setup((hydrate: () => void) => {+ doHydrate = hydrate+ })+ await new Promise(r => setTimeout(r))++ const button = container.querySelector('button')!+ button.remove()+ expect(() => doHydrate()).not.toThrow()+ button.dispatchEvent(new Event('click'))+ await nextTick()+ expect(button.textContent).toBe('0')+ expect(`Hydration node mismatch`).not.toHaveBeenWarned()+ })++ test('skip hydration when unmounted before strategy fires', async () => {+ let doHydrate: () => void+ const container = await setup((hydrate: () => void) => {+ doHydrate = hydrate+ })+ await new Promise(r => setTimeout(r))++ const button = container.querySelector('button')!+ // e.g. route change while the strategy's trigger is already queued+ container.app.unmount()+ expect(() => doHydrate()).not.toThrow()+ button.dispatchEvent(new Event('click'))+ await nextTick()+ expect(button.textContent).toBe('0')+ })++ test('still hydrates when node detached from document and re-attached', async () => {+ let doHydrate: () => void+ const wrapper = document.createElement('section')+ document.body.appendChild(wrapper)+ const container = await setup(+ (hydrate: () => void) => {+ doHydrate = hydrate+ },+ undefined,+ wrapper,+ )+ await new Promise(r => setTimeout(r))++ // temporarily detached (e.g. moved into KeepAlive's storage container)+ const storage = document.createElement('div')+ storage.appendChild(container)+ doHydrate!()+ wrapper.appendChild(container)+ const button = container.querySelector('button')!+ button.dispatchEvent(new Event('click'))+ await nextTick()+ expect(button.textContent).toBe('1')+ })++ test('still hydrates when node remains attached', async () => {+ let doHydrate: () => void+ const container = await setup((hydrate: () => void) => {+ doHydrate = hydrate+ })+ await new Promise(r => setTimeout(r))++ doHydrate!()+ const button = container.querySelector('button')!+ button.dispatchEvent(new Event('click'))+ await nextTick()+ expect(button.textContent).toBe('1')+ })++ test('hydrateOnVisible: node detached before observer callback', async () => {+ const original = (window as any).IntersectionObserver+ let observerCb: ((entries: any[]) => void) | undefined+ ;(window as any).IntersectionObserver = class {+ constructor(cb: (entries: any[]) => void) {+ observerCb = cb+ }+ observe() {}+ disconnect() {}+ }+ try {+ const container = await setup(+ hydrateOnVisible(),+ undefined,+ document.body,+ )+ await new Promise(r => setTimeout(r))+ expect(observerCb).toBeDefined()++ const button = container.querySelector('button')!+ button.remove()+ expect(() => observerCb!([{ isIntersecting: true }])).not.toThrow()+ button.dispatchEvent(new Event('click'))+ await nextTick()+ expect(button.textContent).toBe('0')+ } finally {+ ;(window as any).IntersectionObserver = original+ }+ })++ test('no strategy: node removed while loading', async () => {+ let resolve: (c: any) => void+ const container = await setup(+ undefined,+ () => new Promise(r => (resolve = r)),+ )+ const button = container.querySelector('button')!+ button.remove()+ // hydration runs inside load().then(), so a crash surfaces as an+ // unhandled rejection+ const rejections: unknown[] = []+ const onRejection = (e: unknown) => rejections.push(e)+ process.on('unhandledRejection', onRejection)+ try {+ resolve!(Comp)+ await new Promise(r => setTimeout(r))+ } finally {+ process.off('unhandledRejection', onRejection)+ }+ expect(rejections).toEqual([])+ button.dispatchEvent(new Event('click'))+ await nextTick()+ expect(button.textContent).toBe('0')+ })+ })+ test('hydrate safely when property used by async setup changed before render', async () => { const toggle = ref(true) packages/runtime-core/src/apiAsyncComponent.tsindex 66cb15a27..58d1dd993 100644@@ -136,6 +136,13 @@ export function defineAsyncComponent< } return }+ // skip hydration if the component has been unmounted or its SSR node+ // has been detached before lazy hydration performed (e.g. removed by a+ // route change while the strategy's trigger was already queued) -+ // there is nothing to hydrate.+ 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