You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VueUse createFetch生成的函数无法被await正确异步调用问题

问题解决:Pinia中正确使用VueUse createFetch的异步调用

问题出在链式调用时的await时机错误:json()方法返回的是Promise对象,你直接在其后访问.data会获取到Promise本身的data属性(该属性不存在,所以返回undefined),而非API响应的数据。

修正后的Pinia Action代码

async signin() {
  // 先await json()的结果,再提取data
  const { data } = await authServer("login")
    .post({
      email: "myname@eample.com",
      password: "password",
    })
    .json();
  
  this.signedIn = true;
  console.log(data);
  const credentials = data.msg.split("|");
  this.user.email = credentials[0];
  this.user.firstName = credentials[1];
  this.user.lastName = credentials[2];
  this.user.role = credentials[3];
}

额外优化建议

在defineServer的beforeFetch钩子中,建议先初始化headers对象,避免原请求没有headers时赋值Authorization报错:

beforeFetch(ctx) {
  // 确保headers存在
  ctx.options.headers = ctx.options.headers || {};
  ctx.options.headers.Authorization = token.value;
  return ctx;
},

内容的提问来源于stack exchange,提问作者meljturner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 22:36:29