首页 > 解决方案 > 使用可选链接接收 TypeError:无法读取未定义的属性“数据”

问题描述

我收到错误:

instrument.js:110 TypeError: Cannot read property 'data' of undefined
    at useScenariosGraphql.tsx:128
    at _o (react-dom.production.min.js:231)
    at Du (react-dom.production.min.js:278)
    at t.unstable_runWithPriority (scheduler.production.min.js:19)
    at ql (react-dom.production.min.js:130)
    at Fu (react-dom.production.min.js:277)
    at react-dom.production.min.js:277
    at A (scheduler.production.min.js:17)
    at MessagePort.x.port1.onmessage (scheduler.production.min.js:14)

这发生在这里:

  useEffect(() => {
    let message: string | undefined;
    const error = createError ?? updateError;
    if (error) {
      if (
        // @ts-ignore
        error.graphQLErrors?.[0].data?.messages?.[0] // <---- ERROR HERE Line 128
      )
        // @ts-ignore
        message = error.graphQLErrors?.[0].data?.messages?.[0];
      if (error?.message.includes('same organization as the scenario'))
        message =
          'To create a new scenario, all target areas must be in the same organization as that scenario. You can fix this in the data tab at the top.';
      // @ts-ignore
      if (typeof error?.graphQLErrors?.[0].data?.errors?.[1]?.data?.messages?.[0] === 'string')
        // @ts-ignore
        message = error?.graphQLErrors?.[0].data?.errors?.[1]?.data?.messages?.[0];
      if (!message) {
        message = `Something went wrong with the network request`;
        console.log(error.message);
      }

      addToast(message, 10000);
    }
  }, [addToast, createError, updateError]);

@ts-ignore是因为 GraphQL 错误类型没有数据属性,但返回的对象有时会从 GraphQL 后端。

无论哪种方式,如果它存在或不存在,为什么data我在使用可选链接时无法读取 undefined ?当它没有找到数组0的索引时,它不应该解析为 undefined吗?graphQLErrors

我们知道变量error存在是因为 if 语句。所以现在我正在检查error.graphQLErrors[0]哪个是undefined......但这就是我使用可选链接而不是冗长的原因:

  if (
    error.graphQLErrors[0] &&
    error.graphQLErrors[0].data &&
    error.graphQLErrors[0].data.messages[0]
  )

但它没有按预期工作......请帮助。


编辑

好的,我看到我也需要?在索引之后。第一个问号是说索引是否真的存在,第二个问号是否该索引处的值不是空值variable?.[0]?

标签: javascripttypescript

解决方案


?访问graphQLErrors数组时缺少可选的链接运算符:

error.graphQLErrors?.[0].data?.messages?.[0]

改成:

error.graphQLErrors?.[0]?.data?.messages?.[0]

推荐阅读