Backtestsvuerun-20261021-133314#15153
Custom elements: async components nested ≥3 levels crash with TypeError: Cannot read properties of null (reading 'provides') — chained child resolve races its parent's mount
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches attack the same root cause: the child's chain promise settled when the parent's `_resolveDef()` returned rather than when the parent mounted. Patch A fixes it by making `_resolveDef()` return the async `_pendingResolve` and returning it from the chain callback; Patch B fixes it by returning `this._pendingResolve` from the chain callback after calling `_resolveDef()`. Both make the chain settle after the parent's `resolve()` (which calls `_mount` synchronously), so the independent 3- and 4-level tests pass under either. B goes further on correctness in a way that is tied to the same crash: it moves the `parent._pendingResolve` check ahead of the `_resolved` check, so an already-resolved child connected under a pending async parent is also deferred instead of mounting immediately into `_inheritParentContext` with `parent._instance === null`. Under A that path still dereferences a null parent instance. A's extra `isConnected` guard is a reasonable hardening against mounting a detached element, but it addresses a pre-existing behavior unrelated to the reported null dereference. On tests, A's test is more deterministic (controlled promise resolution rather than real setTimeout delays), and B's 5/30/1 ms timing-based tests carry some flake risk. However B's suite covers more of the issue's variants table: 3 levels with slow middle, 4 levels with slow intermediates, plain div between levels, a sync middle, and provide/inject propagation at each level, plus the resolved-and-moved case. Both would fail on base. Scope and craft are comparable; B's restructure is slightly larger but clearly commented and keeps the fix readable. Net: B resolves the root cause more completely with broader issue-aligned coverage, outweighing A's cleaner test style.
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
6m 2s
Wall-clock time in the container
Full test suite
No new failures
692 passed · 1 skipped · 693 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
197vs 119 merged
Changed lines, ours vs merged
The issue
View on GitHubVue version
3.5.40 (latest at the time of writing — the inline repro pins it; also reproduced on 3.5.13, 3.5.17, 3.5.30 and 3.6.0-rc.2; 3.4.38 — before the nested-async chaining existed — crashes with the same null dereference in the older _setParent provides copy inside vnode.ce)
Link to minimal reproduction
Steps to reproduce
- Open the reproduction link and watch the console:
mounted x-innernever appears — the element crashes with an unhandledTypeError: Cannot read properties of null (reading 'provides')and never mounts. (The playground variant inserts the nested markup dynamically after thedefine()calls; dynamic and parser-created markup crash identically.) - Parser-created (static server-HTML-style) variant — self-contained single file, no build step (save as
repro.html, serve statically, open in any browser; Chromium, Firefox and WebKit all reproduce):
<!doctype html>
<meta charset="utf-8" />
<title>nested async custom elements repro</title>
<x-outer>
<x-middle>
<div>
<x-inner>inner light dom</x-inner>
</div>
</x-middle>
</x-outer>
<script type="module">
import {
defineCustomElement,
defineAsyncComponent,
h,
} from "https://unpkg.com/vue@3.5.40/dist/vue.esm-browser.js";
// Delays chosen so the middle level settles AFTER its child: outer fast,
// middle slow, inner fast. This crashes on 100% of loads.
const delays = { "x-outer": 50, "x-middle": 300, "x-inner": 10 };
const makeComponent = (name) => ({
name,
mounted() {
console.log(`mounted ${name}`);
},
render() {
return h("div", { style: "display:block;padding:6px;border:1px solid #888" }, [name, h("slot")]);
},
});
const makeLoader = (tag) => () =>
new Promise((resolve) => setTimeout(() => resolve(makeComponent(tag)), delays[tag]));
// Define the three tags parent-first.
for (const tag of ["x-outer", "x-middle", "x-inner"]) {
customElements.define(tag, defineCustomElement(defineAsyncComponent(makeLoader(tag))));
}
window.addEventListener("error", (e) => console.error("UNCAUGHT:", e.message));
window.addEventListener("unhandledrejection", (e) =>
console.error("UNHANDLED REJECTION:", e.reason?.message ?? e.reason),
);
</script>
What is expected?
All three elements mount ancestor-first: mounted x-outer, mounted x-middle, mounted x-inner. The nested-async chaining added in 3.5.0 (37ccb9b, "delay mounting of custom elements with async parent", closing #9341 / #8127 / #9351) exists to guarantee exactly this.
What is actually happening?
mounted x-outer
UNHANDLED REJECTION: Cannot read properties of null (reading 'provides')
mounted x-middle
x-inner crashes in VueElement._mount → _inheritParentContext (runtime-dom — parent._instance.provides is dereferenced guarded only by parent && this._app), never mounts, and is left permanently half-resolved: _resolved: true, _instance: null, shadow root empty. Nothing ever retries it, no error surfaces through app.config.errorHandler, and any provide/inject inheritance it should have received is lost. Its own descendants (at deeper nesting) then crash against it in cascade.
Any additional comments?
Analysis (why depth ≥ 3 is the trigger)
connectedCallback of a child under a pending async parent chains:
this._pendingResolve = parent._pendingResolve.then(() => {
this._pendingResolve = undefined;
this._resolveDef();
});
- For an unchained parent (depth 2),
parent._pendingResolveis the parent's own_resolveDef()flow, which settles after the parent has mounted → 2-level nesting is safe. The variants table below confirms: 2 levels never crash. - For a chained parent (depth ≥ 3),
parent._pendingResolveis itself a chain promise — and that promise settles when the parent's_resolveDef()returns (i.e. when the parent's async load starts), not when the parent mounts.
So once the first unchained ancestor mounts, the whole chain unwinds within a few microtasks: every deeper level's loader fires nearly simultaneously and mount order degenerates to network settlement order. Any child whose async definition settles before its parent has mounted hits _inheritParentContext while parent._instance === null and throws. With real-network chunk timings the victim set varies per load, so in an app this presents as a flaky, page-dependent breakage; with the fixed delays above it is 100% deterministic.
Variants checked (each re-run in a real browser):
| Variant | Result |
|---|---|
| 3 levels, middle slowest | crashes every load |
| 3 levels, inner slowest | clean (race direction confirmed) |
| 2 levels | clean (chained parent required) |
plain <div> between levels | still crashes (structure-independent) |
markup inserted dynamically after all define() calls | still crashes |
| all loaders instant | clean (microtask FIFO protects when nothing is pending) |
_inheritParentContext (#13219, ~3.5.14) did not introduce the race — it converted a pre-existing silent misordering into a hard crash. 3.4.38 (no chaining) and 3.5.13 (chaining, pre-#13219) fail with the same null dereference in the older _setParent provides-copy path.
Suggested direction — either (or both):
- Chain the child to the parent's actual mount, not to
_resolveDef()returning — e.g. resolve the parent's_pendingResolveonly after_mount()has run, so the guarantee the chaining was built for ("ancestor mounts before descendant") holds at any depth. - Guard
_inheritParentContextagainstparent._instance === nulland defer context inheritance until the parent instance exists, instead of throwing away the child permanently on an unhandled rejection.
The two patches
packages/runtime-dom/__tests__/customElement.spec.tsindex a5bea20b8..a021a040c 100644@@ -2210,6 +2210,178 @@ describe('defineCustomElement', () => { expect(barVal).toBe('bar') }) + describe('multiple levels of nested async custom elements', () => {+ const mountedOrder: string[] = []+ const injected: Record<string, any> = {}++ const defineAsyncLevel = (+ tag: string,+ delay: number,+ provideKey?: string,+ injectKeys: string[] = [],+ ) => {+ customElements.define(+ tag,+ defineCustomElement(+ defineAsyncComponent(+ () =>+ new Promise<any>(resolve =>+ setTimeout(+ () =>+ resolve({+ setup() {+ if (provideKey) provide(provideKey, tag)+ for (const key of injectKeys) {+ injected[`${tag}:${key}`] = inject(key)+ }+ onMounted(() => mountedOrder.push(tag))+ },+ render(this: any) {+ return h('div', null, [+ tag,+ renderSlot(this.$slots, 'default'),+ ])+ },+ }),+ delay,+ ),+ ),+ ),+ ),+ )+ }++ beforeEach(() => {+ mountedOrder.length = 0+ for (const key in injected) delete injected[key]+ })++ test('3 levels: middle settles after its child', async () => {+ defineAsyncLevel('my-nested-async-outer', 5, 'outer')+ defineAsyncLevel('my-nested-async-middle', 30, 'middle', ['outer'])+ defineAsyncLevel('my-nested-async-inner', 1, undefined, [+ 'outer',+ 'middle',+ ])+ container.innerHTML =+ `<my-nested-async-outer>` ++ `<my-nested-async-middle>` ++ `<div><my-nested-async-inner>light</my-nested-async-inner></div>` ++ `</my-nested-async-middle>` ++ `</my-nested-async-outer>`++ await new Promise(r => setTimeout(r, 60))+ const inner = container.querySelector(+ 'my-nested-async-inner',+ ) as VueElement+ expect(mountedOrder).toEqual([+ 'my-nested-async-outer',+ 'my-nested-async-middle',+ 'my-nested-async-inner',+ ])+ expect(inner.shadowRoot!.innerHTML).toBe(+ `<div>my-nested-async-inner<slot></slot></div>`,+ )+ expect(injected).toEqual({+ 'my-nested-async-middle:outer': 'my-nested-async-outer',+ 'my-nested-async-inner:outer': 'my-nested-async-outer',+ 'my-nested-async-inner:middle': 'my-nested-async-middle',+ })+ })++ test('4 levels: intermediate levels settle after their children', async () => {+ defineAsyncLevel('my-nested-async4-a', 5, 'a')+ defineAsyncLevel('my-nested-async4-b', 30, 'b')+ defineAsyncLevel('my-nested-async4-c', 20, 'c')+ defineAsyncLevel('my-nested-async4-d', 1, undefined, ['a', 'b', 'c'])+ container.innerHTML =+ `<my-nested-async4-a><my-nested-async4-b><my-nested-async4-c>` ++ `<my-nested-async4-d></my-nested-async4-d>` ++ `</my-nested-async4-c></my-nested-async4-b></my-nested-async4-a>`++ await new Promise(r => setTimeout(r, 100))+ expect(mountedOrder).toEqual([+ 'my-nested-async4-a',+ 'my-nested-async4-b',+ 'my-nested-async4-c',+ 'my-nested-async4-d',+ ])+ expect(injected).toEqual({+ 'my-nested-async4-d:a': 'my-nested-async4-a',+ 'my-nested-async4-d:b': 'my-nested-async4-b',+ 'my-nested-async4-d:c': 'my-nested-async4-c',+ })+ })++ test('3 levels with a sync middle level', async () => {+ defineAsyncLevel('my-nested-mixed-outer', 5, 'outer')+ customElements.define(+ 'my-nested-mixed-middle',+ defineCustomElement({+ setup() {+ provide('middle', 'sync')+ onMounted(() => mountedOrder.push('my-nested-mixed-middle'))+ },+ render(this: any) {+ return h('div', null, [renderSlot(this.$slots, 'default')])+ },+ }),+ )+ defineAsyncLevel('my-nested-mixed-inner', 1, undefined, [+ 'outer',+ 'middle',+ ])+ container.innerHTML =+ `<my-nested-mixed-outer><my-nested-mixed-middle>` ++ `<my-nested-mixed-inner></my-nested-mixed-inner>` ++ `</my-nested-mixed-middle></my-nested-mixed-outer>`++ await new Promise(r => setTimeout(r, 30))+ expect(mountedOrder).toEqual([+ 'my-nested-mixed-outer',+ 'my-nested-mixed-middle',+ 'my-nested-mixed-inner',+ ])+ expect(injected).toEqual({+ 'my-nested-mixed-inner:outer': 'my-nested-mixed-outer',+ 'my-nested-mixed-inner:middle': 'sync',+ })+ })++ test('resolved element moved into a pending async parent', async () => {+ defineAsyncLevel('my-nested-moved-inner', 1, undefined, ['outer'])+ container.innerHTML = `<my-nested-moved-inner></my-nested-moved-inner>`+ await new Promise(r => setTimeout(r, 20))+ const inner = container.querySelector(+ 'my-nested-moved-inner',+ ) as VueElement+ expect(mountedOrder).toEqual(['my-nested-moved-inner'])+ expect(`injection "outer" not found.`).toHaveBeenWarned()++ // unmount the resolved element+ inner.remove()+ await nextTick()++ defineAsyncLevel('my-nested-moved-outer', 10, 'outer')+ container.innerHTML = `<my-nested-moved-outer></my-nested-moved-outer>`+ const outer = container.firstChild as VueElement+ outer.appendChild(inner)++ await new Promise(r => setTimeout(r, 40))+ expect(mountedOrder).toEqual([+ 'my-nested-moved-inner',+ 'my-nested-moved-outer',+ 'my-nested-moved-inner',+ ])+ expect(inner.shadowRoot!.innerHTML).toBe(+ `<div>my-nested-moved-inner<slot></slot></div>`,+ )+ expect(injected['my-nested-moved-inner:outer']).toBe(+ 'my-nested-moved-outer',+ )+ })+ })+ describe('configureApp', () => { test('should work', () => { const E = defineCustomElement(packages/runtime-dom/src/apiCustomElement.tsindex 9e1f3a720..20a8c0cf5 100644@@ -307,17 +307,24 @@ export class VueElement } if (!this._instance) {- if (this._resolved) {+ if (parent && parent._pendingResolve) {+ // delay mounting until the async parent has mounted+ this._pendingResolve = parent._pendingResolve.then(() => {+ this._pendingResolve = undefined+ if (this._resolved) {+ if (!this._instance) this._mount(this._def)+ } else {+ this._resolveDef()+ }+ // if this element is itself async, keep the chain pending until it+ // has resolved and mounted, so that deeper descendants chained to+ // this promise never mount before this element does.+ return this._pendingResolve+ })+ } else if (this._resolved) { this._mount(this._def) } else {- if (parent && parent._pendingResolve) {- this._pendingResolve = parent._pendingResolve.then(() => {- this._pendingResolve = undefined- this._resolveDef()- })- } else {- this._resolveDef()- }+ this._resolveDef() } } }
packages/runtime-dom/__tests__/customElement.spec.tsindex a5bea20b8..27c7121c2 100644@@ -2210,6 +2210,118 @@ describe('defineCustomElement', () => { expect(barVal).toBe('bar') }) + test('nested async custom elements should mount ancestor-first', async () => {+ const mounted: string[] = []+ const OuterComp = defineComponent({+ setup() {+ provide('foo', 'foo')+ },+ mounted() {+ mounted.push('outer')+ },+ render() {+ return h('slot')+ },+ })+ const MiddleComp = defineComponent({+ setup() {+ provide('bar', 'bar')+ },+ mounted() {+ mounted.push('middle')+ },+ render() {+ return h('slot')+ },+ })+ const InnerComp = defineComponent({+ setup() {+ const foo = inject('foo')+ const bar = inject('bar')+ return () => h('div', `${foo}/${bar}`)+ },+ mounted() {+ mounted.push('inner')+ },+ })+ let resolveOuter!: (comp: typeof OuterComp) => void+ let resolveMiddle!: (comp: typeof MiddleComp) => void+ let resolveInner!: (comp: typeof InnerComp) => void+ const outerReady = new Promise<typeof OuterComp>(resolve => {+ resolveOuter = resolve+ })+ const middleReady = new Promise<typeof MiddleComp>(resolve => {+ resolveMiddle = resolve+ })+ const innerReady = new Promise<typeof InnerComp>(resolve => {+ resolveInner = resolve+ })++ const Outer = defineCustomElement(defineAsyncComponent(() => outerReady))+ const Middle = defineCustomElement(defineAsyncComponent(() => middleReady))+ const Inner = defineCustomElement(defineAsyncComponent(() => innerReady))++ customElements.define('async-chain-outer', Outer)+ customElements.define('async-chain-middle', Middle)+ customElements.define('async-chain-inner', Inner)+ container.innerHTML =+ `<async-chain-outer>` ++ `<async-chain-middle>` ++ `<async-chain-inner></async-chain-inner>` ++ `</async-chain-middle>` ++ `</async-chain-outer>`++ resolveInner(InnerComp)+ resolveOuter(OuterComp)+ await new Promise(resolve => setTimeout(resolve))+ resolveMiddle(MiddleComp)+ await new Promise(resolve => setTimeout(resolve))++ const inner = container.querySelector('async-chain-inner') as VueElement+ expect(mounted).toEqual(['outer', 'middle', 'inner'])+ expect(inner.shadowRoot!.innerHTML).toBe('<div>foo/bar</div>')+ })++ test('should not resolve nested custom element after disconnect', async () => {+ const mounted = vi.fn()+ const ParentComp = defineComponent({+ render() {+ return h('slot')+ },+ })+ let resolveParent!: (comp: typeof ParentComp) => void+ const parentReady = new Promise<typeof ParentComp>(resolve => {+ resolveParent = resolve+ })+ const Parent = defineCustomElement(defineAsyncComponent(() => parentReady))+ const Child = defineCustomElement({+ mounted,+ render() {+ return h('div', 'child')+ },+ })++ customElements.define('async-disconnect-parent', Parent)+ customElements.define('async-disconnect-child', Child)+ container.innerHTML =+ `<async-disconnect-parent>` ++ `<async-disconnect-child></async-disconnect-child>` ++ `</async-disconnect-parent>`++ const parent = container.firstChild as VueElement+ const child = parent.firstChild as VueElement+ child.remove()+ resolveParent(ParentComp)+ await new Promise(resolve => setTimeout(resolve))++ expect(mounted).not.toHaveBeenCalled()+ expect(child.shadowRoot!.innerHTML).toBe('')++ parent.appendChild(child)+ expect(mounted).toHaveBeenCalledOnce()+ expect(child.shadowRoot!.innerHTML).toBe('<div>child</div>')+ })+ describe('configureApp', () => { test('should work', () => { const E = defineCustomElement(packages/runtime-dom/src/apiCustomElement.tsindex 9e1f3a720..9422f58d6 100644@@ -313,7 +313,9 @@ export class VueElement if (parent && parent._pendingResolve) { this._pendingResolve = parent._pendingResolve.then(() => { this._pendingResolve = undefined- this._resolveDef()+ if (this.isConnected) {+ return this._resolveDef()+ } }) } else { this._resolveDef()@@ -371,7 +373,7 @@ export class VueElement */ private _resolveDef() { if (this._pendingResolve) {- return+ return this._pendingResolve } // set initial attrs@@ -428,6 +430,7 @@ export class VueElement def.configureApp = this._def.configureApp resolve((this._def = def), true) })+ return this._pendingResolve } else { resolve(this._def) }