使用依赖注入报错:inject() can only be used inside setup() or functional components.
2026/5/3 12:12:45 网站建设 项目流程

这个错误是因为inject()只能在组件的setup()函数或函数式组件中使用。

下面是常见错误和解决方案:

错误1:在 setup 外部使用 inject

<script setup> import { inject, onMounted } from 'vue' // ❌ 错误:在 onMounted 回调中直接调用 inject onMounted(() => { const count = inject('count') // 报错! console.log(count) }) // ✅ 正确:在 setup 顶层使用 const count = inject('count') // 正确! onMounted(() => { console.log(count.value) // 这里使用 count }) </script>

错误2:在方法中调用 inject

<script setup> import { inject } from 'vue' // ❌ 错误:在方法内部调用 inject const handleClick = () => { const count = inject('count') // 报错! console.log(count) } // ✅ 正确:在 setup 顶层获取,在方法中使用 const count = inject('count') // 正确! const handleClick = () => { console.log(count.value) // 这里使用已注入的 count } </script>

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询