[Vue warn]: onUnmounted is called when there is no active component instance to be associated with

[Vue warn]: onUnmounted is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.

当没有活动组件实例要关联时,调用onUnmounted。生命周期注入api只能在setup()执行期间使用。如果您正在使用async setup(),请确保在第一个await语句之前注册生命周期钩子。

报这个警告主要是因为生命周期函数onUnmounted等函数只能在setpu中使用,在延时函数中容易遇到,有可能超出这个范围就会出警告。写了一个小工具解决此问题

import { onUnmounted as _onUnmounted, onMounted as _onMounted } from 'vue'

type Hook = () => void
type LifeHook = (hook: Hook) => any

interface IHookItem {
  hooks: LifeHook
  queue: Hook[]
}

const hookMap: Record<string, IHookItem> = {
  onUnmounted: {
    hooks: _onUnmounted,
    queue: [],
  },
  onMounted: {
    hooks: _onMounted,
    queue: [],
  },
}

export function useLifeHook() {
  const keys = Object.keys(hookMap)
  return keys.reduce(
    (p, key) => {
      const hookItem = hookMap[key]
      hookItem.hooks(() => {
        hookItem.queue.forEach((v) => v())
      })
      return {
        ...p,
        [key]: (hook: Hook) => hookItem.queue.push(hook),
      }
    },
    {} as Record<string, LifeHook>,
  )
}

 使用方法示例

const { onUnmounted } = useLifeHook()
const enter = (el: Element, done: () => void) => {
    el.addEventListener('transitionend', done)
    useTimeout(
      () => {
       
       //延时要处理的逻辑
      },
      undefined,
      onUnmounted,
    )
  }


import { onUnmounted as _onUnmounted } from 'vue'
//延时函数
export function useTimeout(fn: () => void, delay?: number, onUnmounted = _onUnmounted) {
  const timer = setTimeout(fn, delay)
  const clear = () => {
    clearTimeout(timer)
  }
  onUnmounted(clear)
  return clear
}

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值