Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: only allow watch callbacks to be self-triggering #724

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/apis/watch.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Vue from 'vue'
import { ComponentInstance } from '../component'
import { Ref, isRef, isReactive } from '../reactivity'
import {
Expand All @@ -11,6 +12,7 @@ import {
isPlainObject,
isSet,
isMap,
getVueInternalClasses,
} from '../utils'
import { defineComponentInstance } from '../utils/helper'
import { getCurrentInstance, getVueConstructor } from '../runtimeContext'
Expand Down Expand Up @@ -248,6 +250,21 @@ function createWatcher(
// effect watch
if (cb === null) {
let running = false
const { Dep } = getVueInternalClasses()
Dep.prototype.notify = function notify() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should avoid patching prototype methods.

This patching of the prototype will run every time we call a watch, because of the scoped running it might cause problems.

const subs = this.subs.slice()
if (__DEV__ && !Vue.config.async) {
// subs aren't sorted in scheduler if not running async
// we need to sort them now to make sure they fire in correct
// order
subs.sort(function (a: any, b: any) {
return a.id - b.id
})
}
for (var i = 0, l = subs.length; i < l; i++) {
!running && subs[i].update()
}
}
const getter = () => {
// preventing the watch callback being call in the same execution
if (running) {
Expand Down
18 changes: 18 additions & 0 deletions test/v3/runtime-core/apiWatch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
set,
shallowReactive,
nextTick,
createApp,
} from '../../../src'
import Vue from 'vue'

Expand Down Expand Up @@ -247,6 +248,23 @@ describe('api: watch', () => {
expect(cleanup).toHaveBeenCalledTimes(2)
})

it('No notification within effect', async () => {
const root = document.createElement('div')
const fn = jest.fn()
const Comp = {
setup() {
const count = ref(0)
watchEffect(() => {
fn()
count.value = 1
})
},
}
createApp(Comp).mount(root)

await nextTick()
expect(fn).toHaveBeenCalledTimes(1)
})
// it('flush timing: post (default)', async () => {
// const count = ref(0);
// let callCount = 0;
Expand Down