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
相关产品推荐
相关产品推荐

