提交空白React表单触发Cannot read properties of undefined(reading 'author')错误
问题根源
- 后端接口返回状态码错误
创建失败的catch块里你返回的是res.status(201),2xx属于成功状态码,Axios只会把4xx/5xx的响应判定为失败走前端catch,所以提交空白表单时请求反而进入前端的then块。 - then块读取不存在的字段
请求进入then块后,你直接取res.data.post,但创建失败时后端只返回了{err}字段,res.data.post是undefined,执行setSortedData((prevArray) => [res.data.post, ...prevArray])会给sortedData插入一个undefined元素,后续map遍历的时候读取item.author就会抛出你遇到的报错。 - 其他潜在问题
data和sortedData初始值设置为空字符串,但是后续需要作为数组执行sort、map操作,类型不匹配- 给data赋值的useEffect没有添加依赖项,每次组件重渲染都会触发setData,可能导致不必要的更新
修复步骤
- 修改后端接口的错误响应状态码,改成400类错误:
exports.apiPostCreate = function (req, res) { let post = new Post(req.body.text, req.verifiedUser.item.username) post .create() .then((item) => { res.status(201).send({ post: item, msg: "Post successfully created" }) }) .catch((err) => { // 改成400状态码,触发前端Axios的catch res.status(400).send({ err, msg: "Field cannot be left blank" }) }) }
- 修正state的初始值为数组,给useEffect添加依赖:
// 初始值改为空数组 const [sortedData, setSortedData] = useState([]) const [data, setData] = useState([]) // 给useEffect添加posts依赖,只在posts更新时赋值 useEffect(() => { setData(posts) }, [posts])
- 可选优化:前端提交前先做非空校验,避免无效请求
const handleSubmit = (e) => { e.preventDefault() // 先校验内容不为空 if (!body.trim()) { setErrorFlash("Field cannot be left blank") return } // 原有Axios请求逻辑 }
内容的提问来源于stack exchange,提问作者Justin Christopher Domingo
相关产品推荐
相关产品推荐

