使用useNavigate跳转时出现Uncaught (in promise) TypeError错误求助
问题详情
编辑文章提交后,希望跳转到/myblogs页面,用useNavigate钩子实现但跳转失败,控制台抛出错误。手动查看博客页面能看到已更新的文章,不清楚错误原因。
控制台错误信息:
BlogDetail.jsx:51 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'then')
相关代码片段:
const handleSubmit = e => { e.preventDefault(); console.log(inputs); sendRequest().then(data => console.log(data).then(() => navigate('/myBlogs/')) ); };
错误原因
console.log(data)的返回值是undefined,而undefined没有.then()方法,你试图在console.log()的结果上链式调用.then(),这就导致了类型错误。
修复方案
调整handleSubmit的逻辑,把console.log(data)和跳转操作放在同一个.then()回调里即可:
修正后的代码
const handleSubmit = e => { e.preventDefault(); console.log(inputs); sendRequest().then(data => { console.log(data); navigate('/myBlogs/'); // 直接在回调内执行跳转,无需链式then }); };
也可以用async/await写法,更简洁易读:
const handleSubmit = async e => { e.preventDefault(); console.log(inputs); const data = await sendRequest(); console.log(data); navigate('/myBlogs/'); };
额外优化提示
- 代码里存在拼写错误:
descritpion应该是description(在useState解构和sendRequest的请求参数里都有这个问题,虽不影响当前跳转,但可能导致后端接收参数异常) sendRequest函数中,若请求失败res会是undefined,此时访问res.data会报错,建议加异常处理:
const sendRequest = async () => { try { const res = await axios.put(`http://localhost:5000/api/blog/update/${id}`, { title: inputs.title, description: inputs.description, // 修正拼写错误 }); return res.data; } catch (err) { console.log(err); // 这里可以添加错误提示弹窗等逻辑 } };
内容的提问来源于stack exchange,提问作者Krishnadev. V
相关产品推荐
相关产品推荐

