From 97974855cc5cb44400e5bb955ec4c72e27c0ffaf Mon Sep 17 00:00:00 2001 From: Thorsten Luenborg Date: Sun, 5 Dec 2021 12:58:11 +0100 Subject: [PATCH] fix(reactivity): mutating a readonly ref nested in a reactive object should fail. fix: #5042 --- packages/reactivity/__tests__/readonly.spec.ts | 11 +++++++++++ packages/reactivity/src/baseHandlers.ts | 3 +++ 2 files changed, 14 insertions(+) diff --git a/packages/reactivity/__tests__/readonly.spec.ts b/packages/reactivity/__tests__/readonly.spec.ts index 185bb310759..25b71cc02e5 100644 --- a/packages/reactivity/__tests__/readonly.spec.ts +++ b/packages/reactivity/__tests__/readonly.spec.ts @@ -474,4 +474,15 @@ describe('reactivity/readonly', () => { expect(rr.foo).toBe(r) expect(isReadonly(rr.foo)).toBe(true) }) + + test('attemptingt to write to a readonly ref nested in a reactive object should fail', () => { + const r = ref(false) + const ror = readonly(r) + const obj = reactive({ ror }) + try { + obj.ror = true + } catch (e) {} + + expect(obj.ror).toBe(false) + }) }) diff --git a/packages/reactivity/src/baseHandlers.ts b/packages/reactivity/src/baseHandlers.ts index 0fa1c4bc2ea..65595d4ce55 100644 --- a/packages/reactivity/src/baseHandlers.ts +++ b/packages/reactivity/src/baseHandlers.ts @@ -147,6 +147,9 @@ function createSetter(shallow = false) { receiver: object ): boolean { let oldValue = (target as any)[key] + if (isReadonly(oldValue) && isRef(oldValue)) { + return false + } if (!shallow && !isReadonly(value)) { value = toRaw(value) oldValue = toRaw(oldValue)