Backtestsvuerun-20261003-231210#15153

Issue #15153 Merged fix PR #15154 Run 3 Oct 2026 · run-20261003-231210 vuejs/core

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

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches fix the root cause the issue identifies. The bug is that a chained child's `_pendingResolve` settles as soon as `_resolveDef()` returns, rather than after the child actually mounts. Both make the chain promise wait on the child's own async-definition promise, so grandchildren only proceed after their parent has mounted.

**Patch A** has `_resolveDef()` return its pending promise and returns that from the chain callback. It also adds an `isConnected` guard.

**Patch B** returns `this._pendingResolve`, which `_resolveDef()` has just set, from the chain callback. It also adds a `_connected` / `_instance` guard.

On the main scenario (3+ levels with a slow middle level) the two are equivalent, and both tests would fail before the fix and pass after.

The difference is coverage of the same underlying invariant: an ancestor must mount before its descendant.
- Patch A leaves the `this._resolved` branch untouched. An already-resolved element that is re-inserted under a still-pending, chained ancestor mounts immediately. It reaches `_inheritParentContext` while `parent._instance` is null and hits the same null dereference.
- Patch B moves the pending-parent check ahead of the `_resolved` check. Already-resolved elements are therefore also deferred until the parent mounts, and B adds a test for exactly this case, including that `provide`/`inject` inheritance works.
- Patch B also guards against double-mounting (`this._instance` check) and against mounting while detached. A dedicated test covers the detached case.

On test quality, Patch A's 3-level test uses deterministic manual promise resolution and checks both mount order and injected values, which is nice. Patch B's 3-level test relies on real timers (5/30/1 ms, then a 60 ms wait), which is slightly more timing-dependent. It does mirror the issue's repro and checks injection across all levels.

Both diffs are tightly scoped, and B's comments explain the invariant clearly. Because B closes an additional crash path of the same race without added risk, it is the more complete fix.

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

8m 12s

Wall-clock time in the container

Full test suite

No new failures

3,633 passed · 6 skipped · 3,639 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

203vs 119 merged

Changed lines, ours vs merged

Vue 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

https://play.vuejs.org/#eNptVNFu4zYQ/JWBi0IyKssOihaBznYQJC6uRS53OLhPcR4YcW2xoUiCpOQYhv+9ICk7OeBeDHG5Ozs7nuVxdGtM2Xc0qkZzV1thPBz5ziw3SrRGW48jOG2ForvOed2uJLWkfDEEb91B1Xe6NVrFaFNAqy+6U554AUtbnLC1ukXWd5Rt1EbVWjmPRjuPRUjIVSfleKOmU9yTZAeHutGOFJyGbwit4FwSJPUkAzUvyeH2r/XqO4QPyULyCrrzZLFlzhcRaqhyUu8LCKWGyxLrRjjUlrmGHLTC1Wz2K/QWUjPuyjM9npgscET2NongWYU/ZkU4Juyswu+zFIj4WYWrGU7vI7bslS7KYIFcsZbGWCyRHzcKCMcifLRJrnyMI0KpllRKvcuz4QIZfkMqPsUCS4qTjfmWfGcVmjzjos8KHOH8QVKFjAtnJDtUL1LXr58M41yoXfWnefv0oi0nW12ZNzgtBccv19fXGU4FniKngOak9tn4OXU8jX+c6kEzTjaM5NkuTRR+41C0xzerW+Eozy05Lfs0syO/Fi3pzucxGcNl/oNMEXBcDPo/ebZ7HsfmF1MN1VHBvVBc70vG+aon5R+E86TI5lmnGqa4JG7pP6q90CorkNOZJC4yk7Xa5tm/j59vH+8fVvf4vvpndbf+++tjFVXPqbTEnFY3ZUvOsR3h5gbn4DhwA6JzwzJEv/rGEsGznYNhlpSfbIV1vgyZW22RJx092wXbPV3s9dFaH1z1PE6zAvXH/XNl2r8gWPGzBc1/tp/5+7+XlE4DnIYpHskFu6VGoKFTASOZUOCixwv5PZFK2+hKfGPWkZ3UlliobJl97cyAljvPvKjxef3lYQxLxmre1eQgOCkvaiblARM4SroJJYOETqidpMlWSEo1UbjwXJQ9kx2VUZaAiUXSJZsPEi7nZwGXcy76cIzJy7T/UuwaD67b+fR8MZ/GvOl73fSMlSXbz6fpUVwGE849tUYyT9FFc7P8akhF8oOfKmxG56UdemxGUNSTBTOGmHWYQPjLA7QXvokAxupecHJYHwytgivL+dSkPkF4S9vFZhRk2IwG2oHcB0Kj0/8+/flr

Steps to reproduce

  1. Open the reproduction link and watch the console: mounted x-inner never appears — the element crashes with an unhandled TypeError: Cannot read properties of null (reading 'provides') and never mounts. (The playground variant inserts the nested markup dynamically after the define() calls; dynamic and parser-created markup crash identically.)
  2. 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._pendingResolve is 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._pendingResolve is 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):

VariantResult
3 levels, middle slowestcrashes every load
3 levels, inner slowestclean (race direction confirmed)
2 levelsclean (chained parent required)
plain <div> between levelsstill crashes (structure-independent)
markup inserted dynamically after all define() callsstill crashes
all loaders instantclean (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):

  1. Chain the child to the parent's actual mount, not to _resolveDef() returning — e.g. resolve the parent's _pendingResolve only after _mount() has run, so the guarantee the chaining was built for ("ancestor mounts before descendant") holds at any depth.
  2. Guard _inheritParentContext against parent._instance === null and defer context inheritance until the parent instance exists, instead of throwing away the child permanently on an unhandled rejection.

The two patches

Our patch+194 −9
packages/runtime-dom/__tests__/customElement.spec.tsindex a5bea20b8..101dc8cb2 100644@@ -2210,6 +2210,181 @@ describe('defineCustomElement', () => {     expect(barVal).toBe('bar')   }) +  test('3 levels of nested async custom elements w/ slow middle level', async () => {+    const mounted: string[] = []+    const injected: Record<string, unknown> = {}+    const delays: Record<string, number> = {+      'my-el-nested-async-outer': 5,+      'my-el-nested-async-middle': 30,+      'my-el-nested-async-inner': 1,+    }+    const tags = Object.keys(delays)+    tags.forEach((tag, i) => {+      customElements.define(+        tag,+        defineCustomElement(+          defineAsyncComponent(+            () =>+              new Promise<any>(r =>+                setTimeout(+                  () =>+                    r({+                      setup() {+                        provide(`level${i}`, tag)+                        for (let j = 0; j < i; j++) {+                          injected[`${tag}:level${j}`] = inject(`level${j}`)+                        }+                        onMounted(() => mounted.push(tag))+                      },+                      render(this: any) {+                        return h('div', null, [+                          tag,+                          renderSlot(this.$slots, 'default'),+                        ])+                      },+                    }),+                  delays[tag],+                ),+              ),+          ),+        ),+      )+    })++    container.innerHTML =+      `<my-el-nested-async-outer>` ++      `<my-el-nested-async-middle><div>` ++      `<my-el-nested-async-inner>inner</my-el-nested-async-inner>` ++      `</div></my-el-nested-async-middle>` ++      `</my-el-nested-async-outer>`++    await new Promise(r => setTimeout(r, 60))+    expect(mounted).toEqual(tags)+    const inner = container.querySelector(+      'my-el-nested-async-inner',+    ) as VueElement+    expect(inner._instance).not.toBeNull()+    expect(inner.shadowRoot!.innerHTML).toBe(+      `<div>my-el-nested-async-inner<slot></slot></div>`,+    )+    expect(injected).toEqual({+      'my-el-nested-async-middle:level0': 'my-el-nested-async-outer',+      'my-el-nested-async-inner:level0': 'my-el-nested-async-outer',+      'my-el-nested-async-inner:level1': 'my-el-nested-async-middle',+    })+  })++  test('resolved custom element moved under a pending async parent', async () => {+    let fooVal: string | undefined = ''+    let resolveParent!: (def: any) => void+    customElements.define(+      'my-el-pending-async-parent',+      defineCustomElement(+        defineAsyncComponent(() => new Promise<any>(r => (resolveParent = r))),+      ),+    )+    customElements.define(+      'my-el-pending-middle',+      defineCustomElement(+        defineAsyncComponent(+          () =>+            new Promise<any>(r =>+              setTimeout(+                () =>+                  r({+                    render(this: any) {+                      return h('div', null, [+                        renderSlot(this.$slots, 'default'),+                      ])+                    },+                  }),+                10,+              ),+            ),+        ),+      ),+    )+    const Child = defineCustomElement({+      setup() {+        fooVal = inject('foo')+      },+      render() {+        return h('div', null, 'child')+      },+    })+    customElements.define('my-el-resolved-child', Child)++    // resolve & mount the child standalone first, then detach it+    const child = document.createElement('my-el-resolved-child') as VueElement+    container.appendChild(child)+    expect(child.shadowRoot!.innerHTML).toBe('<div>child</div>')+    expect(`injection "foo" not found`).toHaveBeenWarned()+    container.removeChild(child)+    await nextTick()+    expect(child._instance).toBeNull()++    container.innerHTML =+      `<my-el-pending-async-parent><my-el-pending-middle>` ++      `</my-el-pending-middle></my-el-pending-async-parent>`+    const middle = container.querySelector('my-el-pending-middle')!+    // re-insert the resolved child under a chained, still-pending parent+    middle.appendChild(child)+    expect(child._instance).toBeNull()++    resolveParent({+      setup() {+        provide('foo', 'foo')+      },+      render(this: any) {+        return h('div', null, [renderSlot(this.$slots, 'default')])+      },+    })+    await new Promise(r => setTimeout(r, 30))+    expect(child._instance).not.toBeNull()+    expect(child.shadowRoot!.innerHTML).toBe('<div>child</div>')+    expect(fooVal).toBe('foo')+  })++  test('custom element detached while waiting for a pending async parent', async () => {+    let resolveParent!: (def: any) => void+    customElements.define(+      'my-el-detach-async-parent',+      defineCustomElement(+        defineAsyncComponent(() => new Promise<any>(r => (resolveParent = r))),+      ),+    )+    customElements.define(+      'my-el-detach-child',+      defineCustomElement({+        render() {+          return h('div', null, 'child')+        },+      }),+    )++    container.innerHTML =+      `<my-el-detach-async-parent><my-el-detach-child>` ++      `</my-el-detach-child></my-el-detach-async-parent>`+    const child = container.querySelector('my-el-detach-child') as VueElement+    // detach before the parent resolves+    child.remove()++    resolveParent({+      render(this: any) {+        return h('div', null, [renderSlot(this.$slots, 'default')])+      },+    })+    await new Promise(r => setTimeout(r))+    // should not mount while detached+    expect(child._instance).toBeNull()+    expect(child.shadowRoot!.innerHTML).toBe('')++    // mounts once re-attached+    container.appendChild(child)+    expect(child._instance).not.toBeNull()+    expect(child.shadowRoot!.innerHTML).toBe('<div>child</div>')+  })+   describe('configureApp', () => {     test('should work', () => {       const E = defineCustomElement(packages/runtime-dom/src/apiCustomElement.tsindex 9e1f3a720..ef19581f9 100644@@ -307,17 +307,27 @@ export class VueElement     }      if (!this._instance) {-      if (this._resolved) {+      if (parent && parent._pendingResolve) {+        // delay until the async parent has mounted. The chained promise must+        // only settle once this element has mounted as well (i.e. after its+        // own async definition, if any, has resolved), so that deeper+        // descendants chained onto it never mount before it does.+        this._pendingResolve = parent._pendingResolve.then(() => {+          this._pendingResolve = undefined+          // skip if already mounted, or detached while waiting (it will be+          // mounted by the next connectedCallback instead)+          if (this._instance || !this._connected) return+          if (this._resolved) {+            this._mount(this._def)+          } else {+            this._resolveDef()+          }+          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()       }     }   } 
Merged fix · PR #15154+117 −2
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)     }