Confused about vue3's reactive implementation

105 views Asked by At

In vue3's reactive implementation, there is an effectStack. I don't understand why it has to be a stack if the effect will be pop() immediately after push()? Is it possible for the length of effectStack larger than 1?

try {
  enableTracking()
  effectStack.push(effect)
  activeEffect = effect
  return fn()
} finally {
  effectStack.pop()
  resetTracking()
  activeEffect = effectStack[effectStack.length - 1]
}
1

There are 1 answers

1
skirtle On BEST ANSWER

I believe this is because effects can trigger other effects.

For example, a computed property may call out to another computed property, in which case both effects would be running at the same time. In that scenario the 'inner' effect runs before the 'outer' effect has finished and dependencies need to be registered against the correct effect. The 'outer' effect is temporarily stashed away while the 'inner' effect is running and then restored when it finishes.

So the length can be greater than 1 if the call to fn causes recursion back into this same piece of code.