我遇到了一个问题,在pc上一切正常工作,但在手机上,这是一个不同的故事。当请求在pc上完成时,它会在屏幕上提醒用户:"Name is required."等等(我故意没有填写姓名或其他属性)。然而,当我这次在手机上尝试它时,它给我一个错误,Cannot read properties of undefined (reading 'data')
,并给出了const data = await err.response.data;
行的参考有一个代码片段:
try {
const config = {
headers: {
"Context-Type": "application/json",
},
};
const res = await axios.post(
USERS_PATH,
{
name,
surname,
email,
password,
repeatedPassword,
},
config
);
console.log(res.data);
} catch (err) {
const data = await err.response.data;
userCtx.updateAlertMessage(Object.values(data).flat());
}
无论平台如何,它都应该粉碎。要解决这个问题,请在访问数据之前检查响应是否为空。你可以使用?
null检查器。
修改:const data = await err.response?.data;