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

嵌套Axios请求未填充对象属性问题排查与修复

问题分析与修复方案

问题根源

嵌套的higher_fnc调用是异步操作,then回调中的myObj["value"] = con.value会在arr.push(myObj)之后才执行。当你打印arr时,myObj的value属性还未被赋值——虽然后续异步请求完成后value会补上,但此时你已经完成了数组打印,所以看起来像是赋值失败。

修复方案

使用async/await控制异步操作的执行顺序,确保在将myObj推入数组前,嵌套请求的结果已经返回并完成赋值:

const higher_fnc = (query_name) => {
  return axios({
    url: GraphQL_Endpoint,
    method: "post",
    headers: headers,
    data: query_name,
  });
};

// 将外层then的回调改为async函数
higher_fnc({
  query: query1,
  variables: { id: "12345"},
}).then(async (d) => {
    for (const x of d.data) {
        const arr = [];
        for (const node of x.nodes) {
            const myObj = {};
            if (node.id === "56789") {
               // 使用await等待嵌套请求完成
               const res = await higher_fnc({
                   query: query2,
                   variables: { id: "345545"},
               });
               // 请求完成后直接赋值
               for (const con of res.data) {
                    myObj["value"] = con.value;
               }
               myObj["id"] = node.node_id;
            } else {
               myObj["id"] = node.node_id;
               myObj["value"] = node.node_value;
            }
            arr.push(myObj);
        } 
        console.log(arr); // 此时数组中的对象已完成所有属性赋值
    }
});

关键修改点

  • 将外层then的回调函数标记为async,允许内部使用await
  • 对嵌套的higher_fnc调用使用await,等待异步请求返回结果后再执行后续赋值逻辑
  • 去掉嵌套的then回调,直接在await之后处理响应数据,确保myObj的value属性在arr.push(myObj)前完成赋值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 13:18:15