vue3 onMounted中使用await控制台警告warn?

  • 45
广东
onUnmounted(() => {
  chartInstance.dispose();
});

onMounted(async () => {
  chartInstance = echarts.init(map.value as HTMLElement, theme);
  const geoJSON = await getMap('province');
  initChart(geoJSON);
});

image.png

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.

请问这是什么原因,我也没有使用顶层await

回复
阅读 548
2 个回答
xie_zhichao
  • 1.1k
上海市
✓ 已被采纳

stackoverflow 上面有类似的情况,应该是用错了 API,给你参考一下

<script setup lang="ts">
  // import { onMounted } from '@vue/runtime-core'; ❌
  import { onMounted } from 'vue'; ✅

  onMounted(() => {
    console.log('myheader mounted');
  })
</script>

参考:https://stackoverflow.com/que...

你应该单独封装一个 async 方法,然后在 onMounted 里同步调用。

onMounted(() => {
  initChart()
})

async function initChart() {
  chartInstance = echarts.init(map.value as HTMLElement, theme);
  const geoJSON = await getMap('province');
  // 原 initChart 逻辑
}
宣传栏