这个错误是因为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>