React+Apollo查询报错:Cannot read properties of undefined (reading 'concepts')
问题:Apollo refetch后访问data.concepts触发TypeError
原本从Neo4j AuraDB获取概念名称列表功能正常,添加refetch重取逻辑后,出现报错:
Uncaught TypeError: Cannot read properties of undefined (reading 'concepts')
错误出现在Autocomplete组件的options属性访问data.concepts时,即使loading状态已完成。
相关代码
GQL与Apollo Hook代码
import { gql, useMutation, useQuery } from "@apollo/client"; const GET_CONCEPTS = gql` query GetConcepts { concepts { uid name } } `; const { loadingConcepts, errorConcepts, data, refetch } = useQuery(GET_CONCEPTS, { fetchPolicy: "network-only", });
报错的Autocomplete组件代码
<Autocomplete multiple disabled={loadingConcepts} value={broaderConceptsV || null} onChange={(event, newBroaderConcepts) => { setBroaderConcepts(newBroaderConcepts); }} options={loadingConcepts ? [] : data.concepts} getOptionLabel={(option) => option.name} renderInput={(params) => ( <MDInput {...params} variant="outlined" label="Broader Concepts" /> )} />
完整错误信息
index.js:165 Uncaught TypeError: Cannot read properties of undefined (reading 'concepts') react_devtools_backend.js:4026 The above error occurred in the AddConcept component: index.js:165 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'concepts')
解决方法
修改Autocomplete组件的options属性,增加data的存在性判断,确保只有当loadingConcepts为false且data存在时,才访问data.concepts:
options={!loadingConcepts && data ? data.concepts : []}
内容的提问来源于stack exchange,提问作者rvhorton
相关产品推荐
相关产品推荐

