Skip to content

Commit 530be30

Browse files
dssengyyx990803
authored andcommitted
feat(computed): warn if trying to set a readonly computed (vuejs#161)
1 parent 7963c01 commit 530be30

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

packages/reactivity/__tests__/computed.spec.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,16 @@
1-
import { computed, reactive, effect, stop, ref } from '../src'
1+
import {
2+
computed,
3+
reactive,
4+
effect,
5+
stop,
6+
ref,
7+
WritableComputedRef
8+
} from '../src'
9+
import { mockWarn } from '@vue/runtime-test'
210

311
describe('reactivity/computed', () => {
12+
mockWarn()
13+
414
it('should return updated value', () => {
515
const value = reactive<{ foo?: number }>({})
616
const cValue = computed(() => value.foo)
@@ -157,4 +167,14 @@ describe('reactivity/computed', () => {
157167
plusOne.value = 0
158168
expect(dummy).toBe(-1)
159169
})
170+
171+
it('should warn if trying to set a readonly computed', () => {
172+
const n = ref(1)
173+
const plusOne = computed(() => n.value + 1)
174+
;(plusOne as WritableComputedRef<number>).value++ // Type cast to prevent TS from preventing the error
175+
176+
expect(
177+
'Write operation failed: computed value is readonly'
178+
).toHaveBeenWarnedLast()
179+
})
160180
})

packages/reactivity/src/computed.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@ export function computed<T>(
2929
: (getterOrOptions as WritableComputedOptions<T>).get
3030
const setter = isReadonly
3131
? () => {
32-
// TODO warn attempting to mutate readonly computed value
32+
if (__DEV__) {
33+
console.warn('Write operation failed: computed value is readonly')
34+
}
3335
}
3436
: (getterOrOptions as WritableComputedOptions<T>).set
3537

0 commit comments

Comments
 (0)