fix(reactivity): ensure readonly refs can be replaced with new refs in reactive objects (#5310)

fix #5307
This commit is contained in:
Thorsten Lünborg 2022-01-23 14:08:27 +01:00 committed by GitHub
parent 059c63eab7
commit 4be1037f31
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 2 deletions

View File

@ -476,7 +476,7 @@ describe('reactivity/readonly', () => {
expect(isReadonly(rr.foo)).toBe(true)
})
test('attemptingt to write to a readonly ref nested in a reactive object should fail', () => {
test('attemptingt to write plain value to a readonly ref nested in a reactive object should fail', () => {
const r = ref(false)
const ror = readonly(r)
const obj = reactive({ ror })
@ -486,4 +486,15 @@ describe('reactivity/readonly', () => {
expect(obj.ror).toBe(false)
})
test('replacing a readonly ref nested in a reactive object with a new ref', () => {
const r = ref(false)
const ror = readonly(r)
const obj = reactive({ ror })
try {
obj.ror = ref(true) as unknown as boolean
} catch (e) {}
expect(obj.ror).toBe(true)
expect(toRaw(obj).ror).not.toBe(ror) // ref successfully replaced
})
})

View File

@ -150,7 +150,7 @@ function createSetter(shallow = false) {
receiver: object
): boolean {
let oldValue = (target as any)[key]
if (isReadonly(oldValue) && isRef(oldValue)) {
if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) {
return false
}
if (!shallow && !isReadonly(value)) {