nextTick
/* globals MutationObserver */
import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'
export let isUsingMicroTask = false
const callbacks: Array<Function> = []
let pending = false
function flushCallbacks() {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
let timerFunc
// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
p.then(flushCallbacks)
// In problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) setTimeout(noop)
}
isUsingMicroTask = true
} else if (
!isIE &&
typeof MutationObserver !== 'undefined' &&
(isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]')
) {
// Use MutationObserver where native Promise is not available,
// e.g. PhantomJS, iOS7, Android 4.4
// (#6466 MutationObserver is unreliable in IE11)
let counter = 1
const observer = new MutationObserver(flushCallbacks)
const textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
// Fallback to setImmediate.
// Technically it leverages the (macro) task queue,
// but it is still a better choice than setTimeout.
timerFunc = () => {
setImmediate(flushCallbacks)
}
} else {
// Fallback to setTimeout.
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
export function nextTick(): Promise<void>
export function nextTick<T>(this: T, cb: (this: T, ...args: any[]) => any): void
export function nextTick<T>(cb: (this: T, ...args: any[]) => any, ctx: T): void
/**
* @internal
*/
export function nextTick(cb?: (...args: any[]) => any, ctx?: object) {
let _resolve
callbacks.push(() => {
if (cb) {
try {
cb.call(ctx)
} catch (e: any) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
})
if (!pending) {
pending = true
timerFunc()
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
这段代码是 Vue.js
中 nextTick
函数的实现,核心功能是在 DOM
更新后执行回调,同时兼容不同浏览器环境下的异步任务调度。以下从设计思路、核心逻辑、兼容性处理三个维度进行解读:
1. 设计目标与核心思想
异步执行回调:将用户传入的回调函数推入队列,在浏览器下一次“空闲时机”(通过微任务/宏任务实现)批量执行,避免同步阻塞。
优先级策略:优先使用微任务(Microtask
,如 Promise.then
),因为微任务优先级高于宏任务(如 setTimeout
),能更快响应 DOM
变化;当微任务不可用时降级为宏任务。
错误处理:通过 try-catch
捕获回调执行时的错误,调用 handleError
统一处理,避免回调链崩溃。
2. 核心逻辑拆解
(1)回调队列管理
const callbacks: Array<Function> = []; // 回调队列
let pending = false; // 标记是否正在处理队列
function flushCallbacks() {
pending = false; // 重置状态
const copies = callbacks.slice(0); // 复制当前队列(避免后续操作污染)
callbacks.length = 0; // 清空队列
copies.forEach(copy => copy()); // 执行所有回调
}
批量执行:每次执行前复制队列,避免新加入的回调被立即执行。
状态标记:pending
防止重复触发调度(如连续调用 nextTick
时,只触发一次 timerFunc
)。
(2)异步调度策略(timerFunc
)
根据浏览器环境选择最优的异步方法,优先级为:Promise > MutationObserver > setImmediate > setTimeout
。
// 优先使用 Promise(微任务)
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve();
timerFunc = () => {
p.then(flushCallbacks);
// iOS 特殊处理:防止微任务队列阻塞
if (isIOS) setTimeout(noop);
};
isUsingMicroTask = true; // 标记使用微任务
}
Promise
方案:利用 Promise.resolve().then()
将 flushCallbacks
推入微任务队列。iOS
需额外 setTimeout(noop)
触发宏任务“解堵”,避免微任务队列积压(如频繁点击触发大量微任务)。
// 降级方案:MutationObserver(微任务)
} else if (!isIE && typeof MutationObserver !== 'undefined') {
let counter = 1;
const observer = new MutationObserver(flushCallbacks);
const textNode = document.createTextNode(String(counter));
observer.observe(textNode, { characterData: true });
timerFunc = () => {
counter = (counter + 1) % 2; // 交替修改文本内容
textNode.data = String(counter); // 触发 MutationObserver
};
isUsingMicroTask = true;
}
MutationObserver
方案:通过修改文本节点的 characterData 触发 mutation 事件(微任务)。需排除 IE(因 IE11 的 MutationObserver 存在 bug)。
// 再次降级:setImmediate(宏任务,优于 setTimeout)
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
timerFunc = () => {
setImmediate(flushCallbacks);
};
}
// 终极降级:setTimeout(宏任务)
} else {
timerFunc = () => {
setTimeout(flushCallbacks, 0);
};
}
setImmediate/setTimeout 方案:宏任务优先级低于微任务,但兼容性更广(如 IE9+)。
(3)nextTick 接口设计
export function nextTick(cb?: Function, ctx?: object): Promise<void> | void {
let _resolve;
callbacks.push(() => {
if (cb) {
try {
cb.call(ctx); // 执行回调(绑定上下文)
} catch (e) {
handleError(e, ctx, 'nextTick'); // 统一错误处理
}
} else if (_resolve) {
_resolve(ctx); // 返回 Promise 时的 resolve
}
});
if (!pending) {
pending = true;
timerFunc(); // 触发异步调度
}
// 支持 Promise 调用
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve;
});
}
}
多态支持:可传入回调函数,或返回 Promise
(如
await nextTick()`)。
上下文绑定:通过 cb.call(ctx)
确保回调执行时的 this
正确。
错误隔离:单个回调的错误不会影响其他回调执行。
3. 兼容性关键点
iOS 微任务阻塞:在 iOS 9.3-10.3
的 UIWebView
中,频繁触发微任务会导致队列阻塞。通过 setTimeout(noop)
强制插入一个宏任务“解堵”。
IE
排除 MutationObserver
:IE11
的 MutationObserver
存在 bug,故直接降级为 setImmediate
。
PhantomJS/旧版 iOS 检测:通过 isNative
和 toString
判断 MutationObserver
是否可用(如 PhantomJS
的 MutationObserver
是 polyfill
,需特殊处理)。
4. 设计取舍与思考
微任务 vs 宏任务:微任务优先级高,但可能导致“顺序问题”(如连续触发多个微任务时,用户代码在中间插入)。Vue 选择优先微任务,仅在明确有兼容问题时降级。
性能优化:批量执行回调(callbacks.slice(0)
)避免多次触发重排/重绘。
错误边界:统一通过 handleError
捕获异常,防止回调链断裂。
总结:这段代码是 Vue 异步更新机制的核心,通过灵活的异步任务调度策略,在保证 DOM
更新后执行回调的同时,最大化兼容性和性能。其设计思想对理解浏览器事件循环、异步编程模式有重要参考价值。
本文地址:https://www.tides.cn/p_vue-source-next-tick