【发布时间】:2026-02-16 08:40:01
【问题描述】:
我对 javascript 很陌生,我正在构建一个 react/flux 应用程序并使用 jquery 对后端进行同步“ajax”调用(sjax?)。我的行为不一致,因为(我认为)我的 ajax 调用没有阻塞,尽管使用了 async:false。关键代码片段如下。
执行流程从带有 ActionTypes.LOGIN 案例的 Flux 存储开始,然后移动到 fetchAccount(action.value);,并且应该同步跟随 AppStore.emitChange();
问题是如果我调用 AppStore.emitChange();在我的 $.ajax 成功函数中,我能够保证 AppStore.emitChange();出现在成功函数之后,否则如果 AppStore.emitChange() 出现在 fetchAccount(action.value) 调用之后,它将在 $.ajax 成功函数完成之前执行。
在我的 Flux Store 中,我调用了一个辅助函数,然后发出一个更改:
// Register callback to handle all updates
AppDispatcher.register(function(action) {
var text;
switch(action.actionType) {
case ActionTypes.LOGIN:
fetchAccount(action.value);
//if i put AppStore.emitChange(); here it's invoked
//before fetchAccount completes even though the $.ajax call is async: false
AppStore.emitChange();
break;
//... code ommitted ...
}
});
我的辅助函数执行 ajax 调用:
function fetchAccount(email) {
$.ajax({
url: "http://www.foo.com/api/accounts/" + email,
jsonp: "callback",
dataType: 'jsonp',
type: 'GET',
async: false,
headers: {"Accept" : "application/javascript; charset=utf-8"},
success: function(data) {
user = data;
currentViewState = AppStates.CONTENT_VIEW;
//AppStore.emitChange(); ---> if i emitChange here it works
},
error: function(xhr, status, err) {
user = "";
currentViewState = AppStates.LOGIN_VIEW;
}
});
};
【问题讨论】:
-
永远不要使用
async: false;这是可怕的做法。您确实应该重构您的代码以使用$.ajax方法提供的异步事件处理程序。 -
Np,我会阅读并更改它。 async: false 有什么问题?
-
问题是因为它锁定了 UI 线程,所以在发出请求时浏览器窗口不会更新。这在用户看来就像浏览器崩溃了,而实际上它只是在更新之前等待来自服务器的响应。
-
嗯,我不确定如何调整它以使用异步处理程序。我想我只需要使用 ajaxComplete 但我只看到如何将它附加到 dom 元素。
-
从您的基本代码来看,您似乎只需要从
success处理程序中调用emitChange(),并将data和AppStates.CONTENT_VIEW作为参数传递:AppStore.emitChange(data, AppStates.CONTENT_VIEW);
标签: javascript jquery ajax flux