提交数据到数据库触发TypeError: callback is not a function错误排查
TypeError: callback is not a function 错误排查与解决
测试向数据库提交数据时反复触发TypeError: callback is not a function错误,调试后仍未定位根因,怀疑传递错误时submitError未定义,但已确认回调函数关联逻辑无误。错误具体出现在catch回调中,且相同代码在其他项目可正常运行。
前端代码
import axios from "axios" import apiBaseUrl from "../../utils/apiBaseUrl.js" export default function(title, customer, description, billed, tags, location, notes, images, jobtype, callback) { axios.post(`${apiBaseUrl}/jobs/create-new`, { title: title, customer: customer, description: description, billed: billed, tags: tags, location: location, notes: notes, jobtype: jobtype, images: images }, { withCredentials: true }) .then(function(response) { callback(response.data) }) .catch(function(error) { callback({submitError: true}) }) }
后端API代码
createNewJob: function(title, customer, description, billed, tags, location, notes, images, jobtype, callback) { JobModel.findOne({$or: [{title: title}, {customer: customer}]}).exec(function(error, job) { if (error) { callback({submitError: true}) } else if (job) { callback({alreadyExistsError: true}) } else { const arrayOfTags = tags.split(",").map(function(tag){ return tag.trim() }) const arrayOfNotes = notes.split(",").map(function(note){ return note.trim() }) } const newJob = new JobModel({ id:randomstring.generate(12), title: title, customer: customer, description: description, billed: billed, tags: arrayOfTags, location: location, notes: arrayOfNotes, jobtype: jobtype, images: images }) newJob.save(function(saveError) { if(saveError) { callback({submitError: true}) } else { callback({success:true}) } }) }) }
核心问题分析与修复方案
后端重复调用callback导致引用失效
后端findOne的回调逻辑中,当error或job已存在时,调用callback后未终止后续代码执行,会继续走到newJob.save再次调用callback。如果第一次调用后外部逻辑已释放回调函数引用,第二次调用时就会触发callback is not a function错误。同时原代码中arrayOfTags和arrayOfNotes仅在else块内定义,若未进入else分支,后续创建newJob时会引用未定义变量,属于潜在bug。修复方式:createNewJob: function(title, customer, description, billed, tags, location, notes, images, jobtype, callback) { JobModel.findOne({$or: [{title: title}, {customer: customer}]}).exec(function(error, job) { if (error) { callback({submitError: true}); return; // 终止后续执行 } else if (job) { callback({alreadyExistsError: true}); return; // 终止后续执行 } const arrayOfTags = tags.split(",").map(tag => tag.trim()); const arrayOfNotes = notes.split(",").map(note => note.trim()); const newJob = new JobModel({ id:randomstring.generate(12), title: title, customer: customer, description: description, billed: billed, tags: arrayOfTags, location: location, notes: arrayOfNotes, jobtype: jobtype, images: images }); newJob.save(function(saveError) { if(saveError) { callback({submitError: true}); } else { callback({success:true}); } }) }) }前端添加防御性判断避免无效调用
检查调用前端导出函数的代码,确认每次都传入有效回调函数。也可在前端代码中添加判断,避免调用非函数:.then(function(response) { typeof callback === 'function' && callback(response.data); }) .catch(function(error) { typeof callback === 'function' && callback({submitError: true}); })
内容的提问来源于stack exchange,提问作者pyrotundra
相关产品推荐
相关产品推荐

