使用Ant Design DatePicker时出现TypeError: Cannot read properties of undefined (reading 'toString')
Ant Design DatePicker 报错 TypeError: Cannot read properties of undefined (reading 'toString')
我在使用Ant Design的DatePicker组件时遇到TypeError,提示“Cannot read properties of undefined (reading 'toString')”。已经定位到问题出在DatePicker,但找不到具体原因。错误栈显示问题发生在dayjs库的m2.isValid函数中,但我既没有在代码里显式调用toString方法,也没有直接访问personalInfo.dateOfBirth属性。
相关代码
表单中的DatePicker组件
<div className="info-div w-33"> <p> <Form.Item label={<h4 className="text-center" style={{ paddingBottom: 0, marginBottom: 0 }}>Date of Birth</h4>} name={["personalInfo", "dateOfBirth"]} rules={[ { required: true, message: 'Please input your Date of Birth!', } ]} > <DatePicker style={{ width: "375px", height: "32px" }} format="DD-MM-YYYY" /> </Form.Item> </p> </div>
表单提交逻辑
const onFinish = (values) => { const cleanData = removeUndefined(values); cleanData.user = auth.currentUser._id; cleanData.agency = auth.currentUser.createdBy; createStudentProfile(cleanData).then(res => { console.log(res); if (res) { navigate("/dashboard"); } }); };
API请求代码
export const createStudentProfile = async (body) => { try { console.log(body); const { data } = await axiosInstance.post("/student/create", body); toast.success("Successfully created student profile"); return data; } catch (e) { console.log(e); if (e?.response?.status === 400) { toast.error(e.response.data.error); return false; } else { toast.error("A server error occurred"); } } };
提交的body示例
{ "academicQualification": { "countryOfEducation": "Chad", "highestLevelOfEducation": "Post Graduate", "education": [] }, "_id": "6451e6b8473271e4c1c0d52b", "personalInfo": { "gender": "Male", "dateOfBirth": "这是一个日期对象,无法直接复制显示", "maritalStatus": "Unmarried", "_id": "6451e6b8473271e4c1c0d52c" }, "nationalityInfo": {}, "mailingAddress": {}, "permanentAddress": {}, "backgroundInfo": {}, "importantContact": {}, "passportInfo": {}, "agency": "6442c63764532ecc839a4cf9", "workExperience": [] }
我之前看到过类似问题有人建议用可选链操作符(?.),但我并没有显式调用toString,不确定这个方案是否适用,希望能得到解决方法。
可能的解决方案
1. 检查removeUndefined函数逻辑
报错核心原因是dateOfBirth被误处理成undefined,导致dayjs内部校验时调用toString失败。仔细检查removeUndefined函数,确认它不会把有效的日期对象判定为“空值”而删除。
2. 手动控制DatePicker的值
给DatePicker添加状态管理,确保值始终是有效的dayjs对象或null,避免出现undefined:
import { useState } from 'react'; import dayjs from 'dayjs'; // 组件内部 const [dateOfBirth, setDateOfBirth] = useState(null); // 修改Form.Item中的DatePicker <DatePicker style={{ width: "375px", height: "32px" }} format="DD-MM-YYYY" value={dateOfBirth} onChange={(date) => setDateOfBirth(date)} />
3. 完善表单校验规则
在Form.Item的rules里添加类型校验,确保值是有效的日期对象:
rules={[ { required: true, message: 'Please input your Date of Birth!', }, { type: 'object', message: '请选择有效的日期!', validator: (_, value) => { return value?.isValid() ? Promise.resolve() : Promise.reject(new Error('无效的日期')); } } ]}
4. 提交前转换日期格式
如果后端需要字符串格式的日期,可以在提交前把日期对象转换为指定格式的字符串,避免序列化问题:
const onFinish = (values) => { const cleanData = removeUndefined(values); // 转换日期为字符串 if (cleanData.personalInfo?.dateOfBirth) { cleanData.personalInfo.dateOfBirth = cleanData.personalInfo.dateOfBirth.format("DD-MM-YYYY"); } cleanData.user = auth.currentUser._id; cleanData.agency = auth.currentUser.createdBy; createStudentProfile(cleanData).then(res => { console.log(res); if (res) { navigate("/dashboard"); } }); };
内容的提问来源于stack exchange,提问作者Abdur Rahman Talha
相关产品推荐
相关产品推荐

