vue3使用onMounted警告:onMounted is called when there is no active component instance to be associated with

在vue3项目中运行后,警告提示:

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在没有要关联的活动组件实例时被调用。生命周期注入API只能在执行setup()期间使用。如果使用async setup(),请确保在第一个wait语句之前注册生命周期挂钩

从上述描述中,可以得知是onMounted顺序的问题。

解决办法:

改变onMounted顺序,将onMounted函数放在最前面。

<script lang="ts">
import { defineComponent , reactive,onMounted } from 'vue';
export default defineComponent({
components:{},
setup() {
const router = useRoute()
onMounted(() => {
//执行方法
})
return {}
}
})
</script>

将onMounted放置最前面后,再次运行项目。


六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!