Backtestsvuerun-20261005-124535#5081
Throw an error on createVNode with using innerHTML and children at the same time
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
The issue is a runtime crash (`Cannot read properties of undefined (reading '__asyncLoader')`). It happens when an element's `innerHTML` and its children change dynamically. Once `innerHTML` has overwritten the DOM, the renderer tries to diff or unmount stale child DOM nodes. The user expects no error, with `innerHTML` taking precedence when set and the children rendering otherwise. Patch A changes `patchElement` in the renderer. When the old vnode had `innerHTML`/`textContent`, it does not try to diff the old children against DOM that no longer exists. Instead it unmounts the old vnode children so component unmount hooks still run. It then mounts the new children fresh and re-applies the content prop when it is unchanged, since the props patch would otherwise skip it. It also stops the optimized `PatchFlags.TEXT` path from clobbering `innerHTML`/`textContent`. This addresses the root cause. Its tests exercise the reported toggle scenarios: - text children - array children with keyed reordering and a child component's `unmounted` hook - `textContent` - a compiled-style block with `TEXT | PROPS` flags These tests would fail or crash before the change. Patch B only adds a dev-mode warning in `createBaseVNode` when `innerHTML`/`textContent` is non-null and children are present. It explicitly does not warn when the prop is nullish, which is exactly the issue's repro (`innerHTML: undefined`). It makes no change to the renderer, so the crash still happens when the values toggle at runtime. Its tests only check that warnings are emitted. Patch B therefore does not fix the reported bug. Patch A is more complex and adds some risk in the patch path, but it is the only one that is correct.
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
13m 51s
Wall-clock time in the container
Full test suite
No new failures
3,647 passed · 6 skipped · 3,653 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
175vs 81 merged
Changed lines, ours vs merged
The issue
View on GitHubVersion
3.2.24
Reproduction link
Steps to reproduce
import { createApp, defineComponent, h } from "vue";
const App = defineComponent({
setup() {
return () => h("div", { innerHTML: undefined }, "a");
}
});
createApp(App).mount("#app");
I want to change innerHTML of props and children dynamic at same time.
What is expected?
no Error and use innerHTML if provided or children content.
What is actually happening?
throw an error.
TypeError Cannot read properties of undefined (reading '__asyncLoader')
<!-- generated by vue-issues. DO NOT REMOVE -->
The two patches
packages/runtime-core/src/renderer.tsindex c0fab7373..022f0b2a0 100644@@ -878,7 +878,56 @@ function baseCreateRenderer( hostSetElementText(el, '') } - if (dynamicChildren) {+ const childFlags = n1.shapeFlag | n2.shapeFlag+ if (+ (oldProps.innerHTML != null || oldProps.textContent != null) &&+ (childFlags & ShapeFlags.TEXT_CHILDREN ||+ // inside a parent block (optimized w/o own dynamicChildren), the+ // dynamic descendants are patched by that block - don't remount them+ (childFlags & ShapeFlags.ARRAY_CHILDREN &&+ (dynamicChildren || !optimized)))+ ) {+ // #5131 the old vnode had innerHTML / textContent, which overwrote the+ // DOM of its children (mounted before props), so they can't be diffed+ // against. Unmount the stale children+ // and mount the new ones before the props patch, same as on mount.+ hostSetElementText(el, '')+ if (n1.shapeFlag & ShapeFlags.ARRAY_CHILDREN) {+ unmountChildren(+ n1.children as VNode[],+ parentComponent,+ parentSuspense,+ )+ }+ if (n2.shapeFlag & ShapeFlags.TEXT_CHILDREN) {+ hostSetElementText(el, n2.children as string)+ } else if (n2.shapeFlag & ShapeFlags.ARRAY_CHILDREN) {+ mountChildren(+ n2.children as VNodeArrayChildren,+ el,+ null,+ parentComponent,+ parentSuspense,+ resolveChildrenNamespace(n2, namespace),+ slotScopeIds,+ optimized,+ )+ }+ // the mount above overwrote the content prop, and the props patch+ // below skips it when unchanged, so re-apply it here.+ for (const key of ['innerHTML', 'textContent']) {+ if (newProps[key] != null && newProps[key] === oldProps[key]) {+ hostPatchProp(+ el,+ key,+ null,+ newProps[key],+ namespace,+ parentComponent,+ )+ }+ }+ } else if (dynamicChildren) { patchBlockChildren( n1.dynamicChildren!, dynamicChildren,@@ -953,7 +1002,12 @@ function baseCreateRenderer( // text // This flag is matched when the element has only dynamic text children.- if (patchFlag & PatchFlags.TEXT) {+ // #5131 skipped when innerHTML / textContent takes precedence+ if (+ patchFlag & PatchFlags.TEXT &&+ newProps.innerHTML == null &&+ newProps.textContent == null+ ) { if (n1.children !== n2.children) { hostSetElementText(el, n2.children as string) }packages/runtime-dom/__tests__/patchProps.spec.tsindex 304d9f9c1..610ab6946 100644@@ -1,12 +1,16 @@ import { patchProp } from '../src/patchProp' import {+ createElementBlock, h, nextTick,+ openBlock, ref, render,+ toDisplayString, vModelCheckbox, withDirectives, } from '../src'+import { PatchFlags } from '@vue/shared' describe('runtime-dom: props patching', () => { test('basic', () => {@@ -165,6 +169,119 @@ describe('runtime-dom: props patching', () => { expect(root.innerHTML).toBe(`<div></div>`) }) + // #5131+ test('innerHTML w/ text children', async () => {+ const root = document.createElement('div')+ const html = ref<string | undefined>(undefined)+ const Comp = { render: () => h('div', { innerHTML: html.value }, 'a') }+ render(h(Comp), root)+ expect(root.innerHTML).toBe(`<div>a</div>`)++ html.value = '<b>x</b>'+ await nextTick()+ expect(root.innerHTML).toBe(`<div><b>x</b></div>`)++ html.value = undefined+ await nextTick()+ expect(root.innerHTML).toBe(`<div>a</div>`)++ html.value = '<b>y</b>'+ await nextTick()+ expect(root.innerHTML).toBe(`<div><b>y</b></div>`)+ })++ // #5131+ test('innerHTML w/ array children', async () => {+ const unmounted = vi.fn()+ const Child = { render: () => h('i', 'c'), unmounted }+ const root = document.createElement('div')+ const html = ref<string | undefined>('<b>x</b>')+ const list = ref(['a'])+ const count = ref(0)+ const Comp = {+ render: () =>+ h('div', { innerHTML: html.value, 'data-count': count.value }, [+ ...list.value.map(k => h('span', { key: k }, k)),+ h(Child),+ ]),+ }+ render(h(Comp), root)+ expect(root.innerHTML).toBe(`<div data-count="0"><b>x</b></div>`)++ // re-render with innerHTML unchanged+ count.value+++ await nextTick()+ expect(root.innerHTML).toBe(`<div data-count="1"><b>x</b></div>`)++ list.value = ['b', 'a']+ html.value = '<b>y</b>'+ await nextTick()+ expect(root.innerHTML).toBe(`<div data-count="1"><b>y</b></div>`)++ html.value = undefined+ await nextTick()+ expect(root.innerHTML).toBe(+ `<div data-count="1"><span>b</span><span>a</span><i>c</i></div>`,+ )++ render(null, root)+ expect(root.innerHTML).toBe(``)+ expect(unmounted).toHaveBeenCalled()+ })++ // #5131+ test('textContent w/ children', async () => {+ const root = document.createElement('div')+ const text = ref<string | undefined>('x')+ const Comp = {+ render: () => h('div', { textContent: text.value }, [h('span', 'a')]),+ }+ render(h(Comp), root)+ expect(root.innerHTML).toBe(`<div>x</div>`)++ text.value = undefined+ await nextTick()+ expect(root.innerHTML).toBe(`<div><span>a</span></div>`)++ text.value = 'y'+ await nextTick()+ expect(root.innerHTML).toBe(`<div>y</div>`)+ })++ // #5131 compiled `<div :innerHTML="html">{{ msg }}</div>`+ test('innerHTML w/ dynamic text children (optimized)', async () => {+ const root = document.createElement('div')+ const html = ref<string | undefined>('<b>x</b>')+ const msg = ref('a')+ const Comp = {+ render: () => (+ openBlock(),+ createElementBlock(+ 'div',+ { innerHTML: html.value },+ toDisplayString(msg.value),+ PatchFlags.TEXT | PatchFlags.PROPS,+ ['innerHTML'],+ )+ ),+ }+ render(h(Comp), root)+ expect(root.innerHTML).toBe(`<div><b>x</b></div>`)++ msg.value = 'b'+ await nextTick()+ expect(root.innerHTML).toBe(`<div><b>x</b></div>`)++ html.value = undefined+ await nextTick()+ expect(root.innerHTML).toBe(`<div>b</div>`)++ html.value = '<b>y</b>'+ msg.value = 'c'+ await nextTick()+ expect(root.innerHTML).toBe(`<div><b>y</b></div>`)+ })+ test('textContent unmount prev children', () => { const fn = vi.fn() const comp = {
packages/runtime-core/__tests__/vnode.spec.tsindex 3a88f302b..000ded438 100644@@ -92,6 +92,50 @@ describe('vnode', () => { expect(`VNode created with invalid key (NaN)`).toHaveBeenWarned() }) + // #5081+ describe('children overridden by innerHTML / textContent', () => {+ test('warn on text children', () => {+ createVNode('div', { innerHTML: '<span/>' }, 'hello')+ expect(+ `The \`innerHTML\` prop on <div> will override its children`,+ ).toHaveBeenWarned()+ })++ test('warn on array children', () => {+ createVNode('div', { innerHTML: '<span/>' }, [createVNode('span')])+ expect(+ `The \`innerHTML\` prop on <div> will override its children`,+ ).toHaveBeenWarned()+ })++ test('warn on textContent', () => {+ createVNode('div', { textContent: 'text' }, 'hello')+ expect(+ `The \`textContent\` prop on <div> will override its children`,+ ).toHaveBeenWarned()+ })++ test('no warning when the prop is nullish', () => {+ createVNode('div', { innerHTML: undefined }, 'hello')+ createVNode('div', { innerHTML: null }, 'hello')+ createVNode('div', { textContent: undefined }, 'hello')+ expect(`will override its children`).not.toHaveBeenWarned()+ })++ test('no warning without renderable children', () => {+ createVNode('div', { innerHTML: '<span/>' })+ createVNode('div', { innerHTML: '<span/>' }, '')+ createVNode('div', { innerHTML: '<span/>' }, [])+ expect(`will override its children`).not.toHaveBeenWarned()+ })++ test('no warning for component vnodes', () => {+ const Comp = { props: ['innerHTML'], render: () => null }+ createVNode(Comp, { innerHTML: '<span/>' }, { default: () => 'slot' })+ expect(`will override its children`).not.toHaveBeenWarned()+ })+ })+ test('create with class component', () => { class Component { $props: anypackages/runtime-core/src/vnode.tsindex e9745c503..30d7fdfda 100644@@ -499,6 +499,25 @@ function createBaseVNode( warn(`VNode created with invalid key (NaN). VNode type:`, vnode.type) } + // #5081 validate children that will be silently discarded by innerHTML /+ // textContent. The template compiler already errors on `v-html` / `v-text`+ // used with children, but render functions have no such check.+ if (__DEV__ && props && vnode.shapeFlag & ShapeFlags.ELEMENT) {+ const overwritingProp =+ props.innerHTML != null+ ? 'innerHTML'+ : props.textContent != null+ ? 'textContent'+ : null+ if (overwritingProp && hasContentChildren(vnode.children)) {+ warn(+ `The \`${overwritingProp}\` prop on <${vnode.type as string}> will ` ++ `override its children. Remove either the \`${overwritingProp}\` ` ++ `prop or the children.`,+ )+ }+ }+ // track vnode for block tree if ( isBlockTreeEnabled > 0 &&@@ -528,6 +547,18 @@ function createBaseVNode( export { createBaseVNode as createElementVNode } +/**+ * dev only+ * Whether children would actually render something. Empty text and empty+ * arrays are ignored, mirroring the compiler's `node.children.length` check+ * for `v-html` / `v-text`.+ */+function hasContentChildren(children: VNode['children']): boolean {+ if (isString(children)) return children !== ''+ if (isArray(children)) return children.length > 0+ return false+}+ export const createVNode = ( __DEV__ ? createVNodeWithArgsTransform : _createVNode ) as typeof _createVNodepackages/server-renderer/__tests__/render.spec.tsindex f537a6219..37de08bd4 100644@@ -664,6 +664,9 @@ function testRender(type: string, render: typeof renderToString) { ), ), ).toBe(`<div><span>hello</span></div>`)+ expect(+ `The \`innerHTML\` prop on <div> will override its children`,+ ).toHaveBeenWarned() }) test('textContent', async () => {@@ -678,6 +681,9 @@ function testRender(type: string, render: typeof renderToString) { ), ), ).toBe(`<div>${escapeHtml(`<span>hello</span>`)}</div>`)+ expect(+ `The \`textContent\` prop on <div> will override its children`,+ ).toHaveBeenWarned() }) test('textarea value', async () => {