Skip to content

Commit 4a5733c

Browse files
committed
add warning when injections has been modified
1 parent 3507eb8 commit 4a5733c

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/core/instance/inject.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/* @flow */
22

33
import { hasSymbol } from 'core/util/env'
4+
import { warn } from '../util/index'
45
import { defineReactive } from '../observer/index'
56

67
export function initProvide (vm: Component) {
@@ -30,7 +31,18 @@ export function initInjections (vm: Component) {
3031
let source = vm
3132
while (source) {
3233
if (source._provided && provideKey in source._provided) {
33-
defineReactive(vm, key, source._provided[provideKey])
34+
if (process.env.NODE_ENV !== 'production') {
35+
defineReactive(vm, key, source._provided[provideKey], () => {
36+
warn(
37+
`Avoid mutating a injections directly since the value will be ` +
38+
`overwritten whenever the provided component re-renders. ` +
39+
`injections being mutated: "${key}"`,
40+
vm
41+
)
42+
})
43+
} else {
44+
defineReactive(vm, key, source._provided[provideKey])
45+
}
3446
break
3547
}
3648
source = source.$parent

test/unit/features/options/inject.spec.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,4 +196,25 @@ describe('Options provide/inject', () => {
196196
})
197197
})
198198
})
199+
200+
it('should warn when injections has been modified', () => {
201+
const key = 'foo'
202+
const vm = new Vue({
203+
provide: {
204+
foo: 1
205+
}
206+
})
207+
208+
const child = new Vue({
209+
parent: vm,
210+
inject: ['foo']
211+
})
212+
213+
expect(child.foo).toBe(1)
214+
child.foo = 2
215+
expect(
216+
`Avoid mutating a injections directly since the value will be ` +
217+
`overwritten whenever the provided component re-renders. ` +
218+
`injections being mutated: "${key}"`).toHaveBeenWarned()
219+
})
199220
})

0 commit comments

Comments
 (0)