You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React使用Axios发POST请求报preventDefault相关undefined错误如何解决

问题解决说明

报错直接原因

你遇到的Cannot read properties of undefined (reading 'preventDefault')错误,触发根源是:

  • 你在useEffect钩子中直接无参数调用了sendLaptop函数,此时函数接收的event形参为undefined,调用event.preventDefault()自然会抛出对应异常。而且这个useEffect的逻辑本身不合理,组件刚挂载时用户还没有填写任何表单内容,直接发起请求只会提交空数据。
  • 额外的错误绑定:你给提交按钮<button>绑定了onSubmit事件,但onSubmit是<form>标签的专有事件,按钮上不存在该事件,该绑定无效,不需要额外给提交按钮加提交事件监听,只要保证表单的onSubmit绑定正确即可。

POST请求逻辑问题

你当前的POST逻辑存在以下可优化点:

  • 没有处理异步请求状态:axios.post是异步方法,当前写法没有等待请求完成就直接清空了表单,也没有捕获请求异常、处理成功/失败的反馈
  • 没有做基础的表单校验,用户可以直接提交空值

修正后代码

import React, { useState } from 'react';
import axios from 'axios';

export let Form_Post = () => {
  let [name, setName] = useState('');
  let [price, setPrice] = useState('');
  let [description, setDescription] = useState('');

  let submitName = (e) => {
    setName(e.target.value);
  };

  let submitPrice = (e) => {
    setPrice(e.target.value);
  };

  let submitDescription = (e) => {
    setDescription(e.target.value);
  };

  // 改为异步函数,处理请求状态
  let sendLaptop = async (event) => {
    event.preventDefault();
    // 简单的非空校验,可根据需求扩展
    if (!name || !price || !description) {
      alert('请填写完整信息');
      return;
    }
    try {
      await axios.post('http://localhost:8081/laptop', {
        name: name,
        price: price,
        description: description,
      });
      // 请求成功后再清空表单
      setName('');
      setPrice('');
      setDescription('');
      alert('提交成功');
    } catch (err) {
      console.error('请求失败:', err);
      alert('提交失败,请重试');
    }
  };

  return (
    <form onSubmit={sendLaptop}>
      <input type="text" value={name} onChange={submitName} placeholder="名称" />
      <input type="text" value={price} onChange={submitPrice} placeholder="价格" />
      <input type="text" value={description} onChange={submitDescription} placeholder="描述" />
      {/* 去掉按钮的onSubmit绑定,明确type为submit */}
      <button type="submit">Send</button>
    </form>
  );
};

内容的提问来源于stack exchange,提问作者Dmitry Chernyak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:15:03