TypeError报错求助:无法读取undefined的'0'属性
解决TypeError: Cannot read properties of undefined (reading '0')问题
你遇到的报错核心原因是**response.json()返回的是一个Promise对象**,而非直接解析完成的JSON数据。你直接将这个Promise传入calculateFaceLocation,导致函数内的data实际是Promise实例,自然无法访问data.outputs[0]这类属性。
修复方案
修改fetch的链式调用逻辑,先完成JSON解析,再将实际数据传入calculateFaceLocation:
fetch("https://api.clarifai.com/v2/models/" + MODEL_ID + "/outputs", requestOptions) .then(response => response.json()) // 先解析JSON,拿到实际返回数据 .then(parsedData => calculateFaceLocation(parsedData)) // 把解析后的数据传给处理函数 .then(result => console.log(result)) .catch(error => console.log('error', error));
额外容错建议
为避免后续因API返回格式变化、未检测到人脸等情况再次触发类似错误,建议在calculateFaceLocation中增加逐层属性校验:
const calculateFaceLocation = (data) => { // 逐层检查关键属性是否存在 if (!data?.outputs?.[0]?.data?.regions?.[0]) { console.log("未检测到人脸或API返回数据格式异常"); return; } const clarifaiFace = data.outputs[0].data.regions[0].region_info.bounding_box; const image = document.getElementById('inputImage'); const width = Number(image.width); const height = Number(image.height); console.log(width, height); console.log(clarifaiFace); };
内容的提问来源于stack exchange,提问作者Yane Lobo
相关产品推荐
相关产品推荐

