fix(watch): should not leak this context to setup watch getters

ref #3603
This commit is contained in:
Evan You 2021-05-25 11:10:11 -04:00
parent 9e3708ca75
commit 1526f94edf
2 changed files with 20 additions and 8 deletions

View File

@ -878,6 +878,22 @@ describe('api: watch', () => {
expect(source).toHaveBeenCalledWith(instance) expect(source).toHaveBeenCalledWith(instance)
}) })
test('should not leak `this.proxy` to setup()', () => {
const source = jest.fn()
const Comp = defineComponent({
render() {},
setup() {
watch(source, () => {})
}
})
const root = nodeOps.createElement('div')
createApp(Comp).mount(root)
// should not have any arguments
expect(source.mock.calls[0]).toMatchObject([])
})
// #2728 // #2728
test('pre watcher callbacks should not track dependencies', async () => { test('pre watcher callbacks should not track dependencies', async () => {
const a = ref(0) const a = ref(0)
@ -944,7 +960,7 @@ describe('api: watch', () => {
await nextTick() await nextTick()
expect(spy).toHaveBeenCalledTimes(2) expect(spy).toHaveBeenCalledTimes(2)
}) })
it('watching sources: ref<any[]>', async () => { it('watching sources: ref<any[]>', async () => {
const foo = ref([1]) const foo = ref([1])
const spy = jest.fn() const spy = jest.fn()

View File

@ -189,9 +189,7 @@ function doWatch(
} else if (isReactive(s)) { } else if (isReactive(s)) {
return traverse(s) return traverse(s)
} else if (isFunction(s)) { } else if (isFunction(s)) {
return callWithErrorHandling(s, instance, ErrorCodes.WATCH_GETTER, [ return callWithErrorHandling(s, instance, ErrorCodes.WATCH_GETTER)
instance && (instance.proxy as any)
])
} else { } else {
__DEV__ && warnInvalidSource(s) __DEV__ && warnInvalidSource(s)
} }
@ -200,9 +198,7 @@ function doWatch(
if (cb) { if (cb) {
// getter with cb // getter with cb
getter = () => getter = () =>
callWithErrorHandling(source, instance, ErrorCodes.WATCH_GETTER, [ callWithErrorHandling(source, instance, ErrorCodes.WATCH_GETTER)
instance && (instance.proxy as any)
])
} else { } else {
// no cb -> simple effect // no cb -> simple effect
getter = () => { getter = () => {
@ -371,7 +367,7 @@ export function instanceWatch(
? source.includes('.') ? source.includes('.')
? createPathGetter(publicThis, source) ? createPathGetter(publicThis, source)
: () => publicThis[source] : () => publicThis[source]
: source.bind(publicThis) : source.bind(publicThis, publicThis)
let cb let cb
if (isFunction(value)) { if (isFunction(value)) {
cb = value cb = value