Subscribe on changes!

computed value becomes `undefined` inside `onUnmounted` hook unless it's accessed before

avatar
Jan 26th 2021

Version

3.0.5

Reproduction link

https://codesandbox.io/s/priceless-lalande-eh4wx?file=/src/views/Home.vue

Steps to reproduce

  1. Go to Codesandbox.
  2. Open console window in Codesandbox.
  3. First access "Home" page, then move to "About" page.
  4. You'll see computed value becoming undefined.
  5. If you un-comment console.log(computedObj.value) right above the onUnmounted hook. The value becomes visible inside onMountedhook.

What is expected?

Not sure. Is this expected?

What is actually happening?

Not sure. I think it would be OK for computed or any other reactive value to be undefined inside onUnmounted, but I think it would be better to have consistent behavior.

avatar
Jan 26th 2021

in the unmounted stage, effects have been stopped, and stopped effects (if using a scheduler) return undefined:

https://github.com/vuejs/vue-next/blob/7f086369003b50101849f4bcb8dd2978c1ea87ff/packages/reactivity/src/effect.ts#L86-L88

In that sense, it's expected.

But if we don't want this behaviour for computed, we could implement a check for effect.active in computed's implementation, and run effect.raw() for stopped computeds, around here:

https://github.com/vuejs/vue-next/blob/7f086369003b50101849f4bcb8dd2978c1ea87ff/packages/reactivity/src/computed.ts#L50-L57

The downside would be that the value would no longer be cached, but at least consumers should still be able to get the value.

avatar
Jan 26th 2021

Yeah that's true. Getting back cached computed value sounds right. I think this is tiny issue not sure if it's worth doing something about it, but I can understand it could be confusing because if the computed is accessed once, it looks like computed is working inside unmounted hook... maybe we should document it as an edge case...?

avatar
Jan 26th 2021

I'd personally rather make the change I proposed. The value may not be cached, but you will likely access it once only in that hook, so there's no real performance impact to be expected.