我收到错误:
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错误类型没有数据属性,但有时从GrahphQL后端返回的对象具有数据属性。
无论哪种方式,如果它存在或不存在,为什么当我使用可选链接时,我不能读取未定义的data
? 当它找不到GraphqlErrors
数组的索引0
时,它不应该解析为未定义吗?
我们知道变量error
是由于if语句而存在的。 所以现在我正在检查error.GraphqlErrors[0]
,它是undefined
.。。 但这就是为什么我使用可选的链接,而不是冗长的:
if (
error.graphQLErrors[0] &&
error.graphQLErrors[0].data &&
error.graphQLErrors[0].data.messages[0]
)
但它并不像预期的那样工作。。。 请帮帮我。
编辑
好的,我明白了,我还需要在索引后面加上一个?
。 第一个问号是否表示索引是否实际存在,第二个问号是否表示该索引处的值在变量中不为nullish?.[0]?
访问GraphqlErrors
数组时缺少可选的链接?
运算符:
error.graphQLErrors?.[0].data?.messages?.[0]
更改为:
error.graphQLErrors?.[0]?.data?.messages?.[0]