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

如何在Axios调用的GraphQL Mutation中传递字符串数组?

问题分析与解决方案

你的代码存在几个关键问题导致程序卡住:

  • GraphQL数组格式错误:直接在模板字符串中插入数组res.options,会被转换成arr1,arr2,arr3这种不符合GraphQL语法的格式,GraphQL要求字符串数组必须是["arr1","arr2","arr3"]的形式,这会导致Mutation请求语法错误。
  • 未处理Promise错误:axiosFunc返回的Promise如果出错(比如语法错误导致的请求失败),没有添加catch处理,错误会被静默吞掉,导致程序看起来没有响应。
  • 函数名不匹配:定义的Mutation生成函数是createMut,但调用时用了create_fields,这会直接抛出引用错误,大概率是你粘贴代码时的笔误。

修正后的代码

// 修正数组格式,用JSON.stringify转成GraphQL认可的字符串数组格式
const createMut = (id, res) => `
    mutation {
        createField(input: {
            id: "${id}",
            label: "${res.label}",
            options: ${JSON.stringify(res.options)}
            }) {
            table_field {
              id
              label
            }
        }
    }
`;

// 改用for...of处理Promise,同时添加错误捕获
const myFunc = async (id, result) => {
    for (const d of result.data) {
        try {
            const response = await axiosFunc({ query: createMut(id, d) });
            // 这里可以添加对response的处理逻辑
            console.log(response);
        } catch (error) {
            // 捕获并处理错误,避免静默失败
            console.error('请求失败:', error);
        }
    }
}

额外优化建议

如果需要等待所有Mutation请求完成后再执行后续逻辑,可以用Promise.all:

const myFunc = async (id, result) => {
    const promises = result.data.map(d => {
        return axiosFunc({ query: createMut(id, d) })
            .then(response => {
                // 处理单个请求的成功结果
                return response;
            })
            .catch(error => {
                // 单个请求失败时的处理
                console.error('单个请求失败:', error);
                throw error; // 可选:如果需要让Promise.all整体失败则抛出
            });
    });

    try {
        const allResponses = await Promise.all(promises);
        // 所有请求完成后的逻辑
        console.log('所有请求完成:', allResponses);
    } catch (error) {
        console.error('至少一个请求失败:', error);
    }
}

内容的提问来源于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.22 22:22:50