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

Vue项目中异步调用generateID方法出现undefined报错的问题

解决JavaScript中GraphQL请求返回undefined的报错问题

1. 基础存在性校验

在访问嵌套属性前,先逐层校验数据是否存在,避免因rawID或rawID.data为undefined导致报错:

async click() {
    const rawID = await generateID()
    // 校验rawID及嵌套数据的存在性
    if (!rawID || !rawID.data) {
        console.error('请求失败或返回数据异常')
        return // 终止后续逻辑
    }
    const ID = rawID.data.theDataINeed
    console.log(rawID, ID)
},

generateID() {
    const CREATE_ID = gql`
        mutation {
            theDataINeed
        }
    `
    return this.$axios.post('theGraphQLEndPoint', {
        query: print(CREATE_ID),
    })
},

2. 结合错误捕获与可选链

用try/catch捕获请求过程中的异常,同时使用ES2020的可选链操作符?.安全访问嵌套属性,简化校验逻辑:

async click() {
    try {
        const rawID = await generateID()
        // 用可选链安全访问,若任意层级为undefined则返回undefined
        const ID = rawID?.data?.theDataINeed
        if (ID === undefined) {
            console.error('返回数据格式不符合预期')
            return
        }
        console.log(rawID, ID)
    } catch (error) {
        console.error('请求出错:', error)
        // 可添加用户可见的错误提示,如弹窗
    }
},

generateID() {
    const CREATE_ID = gql`
        mutation {
            theDataINeed
        }
    `
    return this.$axios.post('theGraphQLEndPoint', {
        query: print(CREATE_ID),
    })
},

3. 给请求方法添加兜底返回

让generateID在请求失败时返回一个兜底对象,避免上层拿到undefined:

generateID() {
    const CREATE_ID = gql`
        mutation {
            theDataINeed
        }
    `
    return this.$axios.post('theGraphQLEndPoint', {
        query: print(CREATE_ID),
    }).catch(error => {
        console.error('生成ID请求失败:', error)
        // 返回带空data的对象,保证上层访问不会直接报错
        return { data: {} }
    })
},

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:01:12