Skip to content

Commit ad3cb91

Browse files
committed
fix(provide): warn when using provide after mounting
1 parent 5a8aa0b commit ad3cb91

File tree

2 files changed

+47
-3
lines changed

2 files changed

+47
-3
lines changed

packages/runtime-core/__tests__/apiInject.spec.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
hasInjectionContext,
77
inject,
88
nextTick,
9+
onMounted,
910
provide,
1011
reactive,
1112
readonly,
@@ -372,4 +373,46 @@ describe('api: provide/inject', () => {
372373
})
373374
})
374375
})
376+
377+
describe('warnings for incorrect usage', () => {
378+
it('should warn when inject() is called outside setup', () => {
379+
inject('foo', 'bar')
380+
expect(`inject() can only be used`).toHaveBeenWarned()
381+
})
382+
383+
it('should warn when provide() is called outside setup', () => {
384+
provide('foo', 'bar')
385+
expect(`provide() can only be used`).toHaveBeenWarned()
386+
})
387+
388+
it('should warn when provide() is called from a render function', () => {
389+
const Provider = {
390+
setup() {
391+
return () => {
392+
provide('foo', 'bar')
393+
}
394+
},
395+
}
396+
397+
const root = nodeOps.createElement('div')
398+
render(h(Provider), root)
399+
expect(`provide() can only be used`).toHaveBeenWarned()
400+
})
401+
402+
it('should warn when provide() is called from onMounted', () => {
403+
const Provider = {
404+
setup() {
405+
onMounted(() => {
406+
provide('foo', 'bar')
407+
})
408+
409+
return () => null
410+
},
411+
}
412+
413+
const root = nodeOps.createElement('div')
414+
render(h(Provider), root)
415+
expect(`provide() can only be used`).toHaveBeenWarned()
416+
})
417+
})
375418
})

packages/runtime-core/src/apiInject.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,12 @@ export function provide<T, K = InjectionKey<T> | string | number>(
1111
key: K,
1212
value: K extends InjectionKey<infer V> ? V : T,
1313
): void {
14-
if (!currentInstance) {
15-
if (__DEV__) {
14+
if (__DEV__) {
15+
if (!currentInstance || currentInstance.isMounted) {
1616
warn(`provide() can only be used inside setup().`)
1717
}
18-
} else {
18+
}
19+
if (currentInstance) {
1920
let provides = currentInstance.provides
2021
// by default an instance inherits its parent's provides object
2122
// but when it needs to provide values of its own, it creates its

0 commit comments

Comments
 (0)