Vue3 + TypeScript 生命周期钩子使用错误解析 onMounted is called when there is no active component instance to be

[Vue warn]: onMounted 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.

这个错误表明你在组件中使用了 onMounted 生命周期钩子,但 Vue 无法将其关联到当前组件实例。通常发生在两种场景中:

错误原因分析

  1. 在异步 setup() 中使用 await 后才调用生命周期钩子

  2. 在组件外部(如普通 JS/TS 文件)调用生命周期钩子

根据堆栈信息,问题出现在 useSetTableColumnWidth.ts 文件的第 99 行(在 ReagentTable.vue 中被调用)。


解决方案

情况 1:组合式函数 useSetTableColumnWidth 的问题

如果 useSetTableColumnWidth.ts 中直接调用了 onMounted

typescript

复制

下载

// ❌ 错误写法(在组合式函数中直接调用钩子)
import { onMounted } from 'vue'

export function useSetTableColumnWidth() {
  // 错误!组合式函数中不能直接调用生命周期钩子
  onMounted(() => {
    console.log('mounted')
  })
}

修正方式:将钩子逻辑移入组件

typescript

复制

下载

// ✅ 正确写法:返回需要在组件中调用的方法
import { ref } from 'vue'

export function useSetTableColumnWidth() {
  const initColumns = () => {
    console.log('初始化列宽逻辑')
  }

  // 返回需要在组件中调用的方法
  return { initColumns }
}

在组件中使用:

vue

复制

下载

情况 2:ReagentTable.vue 组件自身问题

如果组件使用了异步 setup 且钩子位置错误:

vue

复制

下载

修正方式:调整钩子注册位置

vue

复制

下载


关键修复原则

  1. 任何生命周期钩子 (onMounted/onUpdated 等) 必须在:

    • 组件的同步 setup 上下文中调用

    •  在异步 setup 的第一个 await 语句之前调用

  2. 组合式函数中:

    • 不要直接调用生命周期钩子

    • 改为返回需要在钩子中执行的方法,由组件控制调用时机


调试建议

  1. 检查 useSetTableColumnWidth.ts 的第 99 行附近代码

  2. 确认 ReagentTable.vue 的 setup 是否包含异步操作:

    vue

    复制

    下载

  3. 如果使用 

你可能感兴趣的:(typescript,前端,vue.js)