fullCalendar 5.5.1调用successCallback后出现undefined错误求助
问题分析与解决方案
错误原因拆解
- 空响应场景:数据库返回空数组时,仅打印日志但未调用
successCallback([])告知fullCalendar无事件数据,导致框架等待回调结果时触发未定义错误。 - 数据解析完成后报错:
successCallback仅需接收事件数组作为唯一参数,错误地将forEach的返回值(undefined)作为第二个参数传入,完全多余。successCallback无返回值,在其后链式调用.catch()相当于对undefined调用方法,直接触发successCallback(...) is undefined错误。.catch()位置错误,应挂载在axios的Promise链上,而非successCallback之后。
修改后的完整代码
var calendar = new Calendar(calendarEl, { timeZone: 'local', customButtons: { newEvent: { text: 'New record', click: function () { alert('clicked the custom button!'); } } }, headerToolbar: { right: 'prev,next today', left: 'title', center: 'newEvent', //right: 'dayGridMonth,dayGridWeek,dayGridDay' }, themeSystem: 'bootstrap', defaultAllDay: true, events: function (info, successCallback, failureCallback) { let user = sessione.profilo.id; let project = sessione.progettoAttivo.id; let start = info.startStr; let end = info.endStr; smartAxios.get("/timesheet?user=" + user + "&project=" + project + "&start=" + start + "&end=" + end) .then((response) => { console.log(response.data); let prevDate = ''; let totDuration = 0; let events = []; if(response.data.length === 0){ console.log('no data for this month'); // 主动告知fullCalendar无事件 successCallback(events); }else{ // 生成fullCalendar所需的事件数组 events = response.data.map(function (eventEl) { console.log(eventEl); return { title: eventEl.title, start: eventEl.start, color: '#007bff', textColor: 'white', allDay: true } }); // 单独处理日期高亮逻辑,不混入successCallback参数 response.data.forEach(function (element) { let date = new Date(element.start); let year = date.getFullYear(); let month = ((date.getMonth()+1).toString().length < 2) ? "0"+(date.getMonth()+1) : (date.getMonth()+1); let day = ((date.getDate()).toString().length < 2) ? "0"+(date.getDate()) : (date.getDate()); date= year+'-'+month+'-'+day; if (date == prevDate) { totDuration = totDuration + element.duration; } else { prevDate = date; totDuration = element.duration; } if (totDuration > 8) { $('#calendar').find('.fc-day[data-date="' + date + '"]').css('background-color', '#FAA732'); } console.log(prevDate, totDuration); }); // 仅传入事件数组给successCallback successCallback(events); } }) // 将catch移到axios请求链末尾,捕获请求错误 .catch(function(err){ console.log(err); $(document).Toasts('create', { autohide: true, delay: 750, title: 'Timesheet', class: 'bg-danger', body:'Error trying to retrieve data' }); // 告知fullCalendar请求失败 failureCallback(err); }); } });
关键改动说明
- 空响应时调用
successCallback([]),明确告知框架无事件数据。 - 拆分日期高亮逻辑,避免向
successCallback传递无效参数。 - 调整
.catch()位置,确保捕获axios请求过程中的错误。 - 出错时调用
failureCallback(err),符合fullCalendar异步事件源规范。
内容的提问来源于stack exchange,提问作者user2399035
相关产品推荐
相关产品推荐

