Nuxt3调用Pinia异步Action返回Promise而非数据问题求助
问题解决:调用Pinia异步Action返回Promise而非数据
问题原因
fetchCountries是带async关键字的异步Action,所有异步函数默认返回Promise对象,所以直接调用countriesStore.fetchCountries()拿到的必然是Promise,而非接口返回的数据。而且你的Action内部仅把数据赋值给了store的countries状态,没有返回数据——就算有返回,也得通过await才能拿到结果。
修正方案
不需要接收Action的返回值,而是通过store的状态或getter获取已存储的数据,同时要await Action执行以确保数据加载完成:
修正后的组件代码
<script lang="ts"> import { useCountriesStore } from '@/stores/countriesStore'; import { onMounted, computed } from 'vue'; export default { setup(){ const countriesStore = useCountriesStore(); // 用computed响应式绑定store中的数据 const countriesData = computed(() => countriesStore.getCountries); // 响应式获取加载状态 const isLoading = computed(() => countriesStore.isLoading); // 封装异步加载逻辑 const loadCountries = async () => { await countriesStore.fetchCountries(); // 数据加载完成后可直接访问store状态 console.log(countriesStore.countries); }; // 组件挂载时触发数据加载 onMounted(() => { loadCountries(); }); return { countriesData, isLoading } } } </script>
额外说明
- 用
computed包裹store状态/getter,能确保组件响应式感知数据变化 - 将异步操作放在
onMounted钩子中,是更合理的执行时机,避免setup阶段的异步阻塞 - 你可以直接用
countriesStore.countries访问状态,也可以用定义好的getCountriesgetter,两者效果一致
内容的提问来源于stack exchange,提问作者ABBY NYAKARA
相关产品推荐
相关产品推荐

