Promise未处理拒绝错误(TypeError):res.json未定义问题修复求助
问题排查:Promise未处理拒绝及TypeError错误
错误提示:WARN Possible Unhandled Promise Rejection (id: 21): TypeError: undefined is not an object (evaluating 'res.json')
已确认user和loggeduserobj输出正常,loggeduserobj为对象类型,但错误仍存在。
前端代码(原代码)
const { user } = route.params; const [issameuser, setIssameuser] = useState(false) const [follow, SetFollow] = useState(false) const isMyProfile = async (otherprofile) => { AsyncStorage.getItem('user').then((loggeduser) => { const loggeduserobj = JSON.parse(loggeduser) if (loggeduserobj.user.username == otherprofile[0].username) { setIssameuser(true) } else { setIssameuser(false) } }) } const CheckFollow = async (otherprofile) => { AsyncStorage.getItem('user') .then(loggeduser => { const loggeduserobj = JSON.parse(loggeduser); fetch('http://10.0.2.2:3000/checkfollow', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ followfrom : loggeduserobj.user.username, followto: otherprofile[0].username }) }) }) .then(res => res.json()) .then(data => { if (data.message == "User in following list") { SetFollow(true) } else if (data.message == "User not in following list") { SetFollow(false) } else { alert('Please Try Again!') } }) } useEffect(() => { isMyProfile(user) CheckFollow(user) }, [])
后端代码(原代码)
router.post('/checkfollow', (req, res) => { const { followfrom, followto } = req.body; console.log(followfrom, followto); if (!followfrom || !followto) { return res.status(422).json({ error: "Invalid Credentials" }); } User.findOne({ username: followfrom }) .then(mainuser => { if (!mainuser) { return res.status(422).json({ error: "Invalid Credentials" }); } else { let data = mainuser.following.includes(followto); console.log(data); if (data == true) { res.status(200).send({ message: "User in following list" }) } else { res.status(200).send({ message: "User not in following list" }) } } }) .catch(err => { return res.status(422).json({ error: "Server Error" }); }) })
错误原因与修复方案
核心错误原因
CheckFollow函数中,第一个.then()(处理AsyncStorage的回调)没有返回fetch请求的Promise,导致后续Promise链断裂,第二个.then()拿到的res是undefined,无法调用res.json()。
修复后的前端代码
const { user } = route.params; const [issameuser, setIssameuser] = useState(false) const [follow, SetFollow] = useState(false) const isMyProfile = (otherprofile) => { AsyncStorage.getItem('user') .then((loggeduser) => { const loggeduserobj = JSON.parse(loggeduser) // 增加数组非空判断,避免越界错误 if (otherprofile.length > 0 && loggeduserobj.user.username === otherprofile[0].username) { setIssameuser(true) } else { setIssameuser(false) } }) .catch(err => console.error('获取本地用户失败:', err)) // 捕获异步操作异常 } const CheckFollow = (otherprofile) => { AsyncStorage.getItem('user') .then(loggeduser => { const loggeduserobj = JSON.parse(loggeduser); // 校验用户数组合法性 if (!otherprofile || otherprofile.length === 0) { alert('用户信息异常'); return; } // 必须返回fetch的Promise,才能延续后续Promise链 return fetch('http://10.0.2.2:3000/checkfollow', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ followfrom: loggeduserobj.user.username, followto: otherprofile[0].username }) }) }) .then(res => { // 先判断请求是否成功,再解析JSON if (!res.ok) { throw new Error(`请求失败: ${res.status}`); } return res.json(); }) .then(data => { if (data.message === "User in following list") { SetFollow(true) } else if (data.message === "User not in following list") { SetFollow(false) } else { alert('Please Try Again!') } }) .catch(err => { // 统一捕获所有Promise异常,避免未处理拒绝警告 console.error('检查关注状态失败:', err); alert('检查关注状态失败,请重试'); }) } useEffect(() => { isMyProfile(user) CheckFollow(user) }, [user]) // 依赖项添加user,路由参数变化时重新执行检查
后端代码优化(可选)
统一用res.json()返回响应,保持格式一致;服务器错误改用500状态码更规范:
router.post('/checkfollow', (req, res) => { const { followfrom, followto } = req.body; console.log(followfrom, followto); if (!followfrom || !followto) { return res.status(422).json({ error: "Invalid Credentials" }); } User.findOne({ username: followfrom }) .then(mainuser => { if (!mainuser) { return res.status(422).json({ error: "Invalid Credentials" }); } const isFollowing = mainuser.following.includes(followto); console.log(isFollowing); if (isFollowing) { res.status(200).json({ message: "User in following list" }) } else { res.status(200).json({ message: "User not in following list" }) } }) .catch(err => { console.error('服务器错误:', err); return res.status(500).json({ error: "Server Error" }); }) })
关键修复点总结
- 返回fetch请求:第一个
.then()必须return fetch(...),确保后续Promise链能拿到响应对象 - 增加异常捕获:所有异步操作添加
.catch(),避免未处理的Promise拒绝警告 - 边界校验:对
otherprofile数组做非空检查,防止数组越界错误 - 优化依赖项:
useEffect依赖数组添加user,确保路由参数变化时重新执行逻辑
内容的提问来源于stack exchange,提问作者user20952626
相关产品推荐
相关产品推荐

