Subscribe on changes!

beforeUnmount triggered before mounted

avatar
Jan 19th 2022

Version

3.2.27

Reproduction link

sfc.vuejs.org/

Steps to reproduce

please review the reproduction code, when organizing the code like this,will happen beforeUnmount is executed before mounted.

if the component Comp not use v-if="flag",work find. Because,renderfunction whill executedflushPostFlushCbs()` after patch.

What is expected?

beforeUnmount triggered before mounted

What is actually happening?

beforeUnmount triggered after mounted

avatar
Jan 19th 2022

I've been thinking about this a bit and now I think this isn't a bug, necessarily.

  • beforeMount and beforeUnmount are called synchronously before the render effect.
  • mounted and unmounted are called on the next Tick after the current scheduler cycle has finished.

So if you have code that 1) mounts a component and during that mount process, 2) triggers an effect that triggers a direct unmount of that same component, the synchronous beforeUnmount will necessarily run before mounted.

What we could look into is to not run mounted anymore if the component has already been starting to unmount before it was called - but that would not solve the challenge in this issue as beforeUnmount would still through.

Rather, we might want to document that anything you set up in mounted, should generally be cleaned up in unmounted, not beforeUnmounted, to avoid race conditions.

avatar
Jan 19th 2022

@LinusBorg

perhaps mounted should not be called, since the component is not technically mounted when it is called.

+1 for the docs update

avatar
Jan 20th 2022

maybe we could code like this,put the action to nexttick

beforeCreate() {
  this.obj = {}
},
mounted() {
  this.obj.a = 1;
},
beforeUnmount() {
  this.$nextTick(()=>{
     delete this.obj;
  })
}
avatar
Jan 20th 2022

maybe we could code like this,put the action to nexttick

no need

export default {
  beforeCreate() {
        this.obj = {}
  },
  mounted() {
    this.obj.a = 1;
  },
  unmounted() {
    delete this.obj;
  }
}