Rax 1.2.x 核心引擎版本演化解读:渲染注入拆分、卸载组件安全更新与兼容包构建修复
Rax 1.2.x 核心引擎版本演化解读:渲染注入拆分、卸载组件安全更新与兼容包构建修复
导读
本文以 packages/rax/CHANGELOG.md 为主线,深入解析 Rax 1.2.1 → 1.2.3 三个补丁版本中关于核心渲染引擎的四项关键改进:渲染相关配置与运行时注入的职责拆分(inject / injectRenderOptions)、lib/compat 兼容包构建路径修复、模块输出格式统一(避免 IIFE 与 CJS 混用),以及卸载组件上状态更新由"抛错"改为"安全告警",并同步修复了 getDerivedStateFromError 错误边界的错误信息缺失问题。读完本文,你将理解 Rax 渲染引擎的配置注入机制、构建产物规范,以及如何编写健壮的异步清理逻辑和错误边界。
一、1.2.3:渲染无关配置与 injectRenderOptions 职责拆分
变更背景与动机
1.2.3 版本的核心变更是:
chore: move the configuration not related to rendering to
injectmethod, others move toinjectRenderOptionsmethod
从源码结构看,这次重构将 Rax 运行时"注入"逻辑按职责一分为二:
| 方法 | 职责 | 挂载位置 |
|---|---|---|
inject() |
注入与渲染无关的运行时组件类与开发工具 | Host.__Empty、Host.__Native、Host.__Text、Host.__Fragment、Host.__Composite、Host.reconciler |
injectRenderOptions() |
注入与渲染直接相关的 driver 与性能度量器 | Host.driver、Host.measurer |
源码级实现解析
inject() 定义在 packages/rax/src/vdom/inject.js,它一次性完成五类内部组件类的注入:
export default function inject() {
// Inject component class
Host.__Empty = EmptyComponent;
Host.__Native = NativeComponent;
Host.__Text = TextComponent;
Host.__Fragment = FragmentComponent;
Host.__Composite = CompositeComponent;
if (process.env.NODE_ENV !== 'production') {
// Inject devtool renderer hook
Host.reconciler = reconciler;
}
}
injectRenderOptions() 定义在 packages/rax/src/vdom/injectRenderOptions.js,只负责接收渲染选项:
export default function injectRenderOptions({ driver, measurer }) {
// Inject render driver
if (!(Host.driver = driver || Host.driver)) {
if (process.env.NODE_ENV !== 'production') {
throwError('Rax driver not found.');
} else {
throwMinifiedError(5);
}
}
if (process.env.NODE_ENV !== 'production') {
// Inject performance measurer
Host.measurer = measurer;
}
}
两者被 packages/rax/src/render.js 串联调用:模块加载时立即执行 inject(),每次 render() 调用时执行 injectRenderOptions(options):
// Inject init options to host, avoid circle deps between class component file and ./vdom/host
inject();
function render(element, container, options, callback) {
// Compatible with `render(element, container, callback)`
if (isFunction(options)) {
callback = options;
options = null;
}
options = options || EMPTY_OBJECT;
// Init inject
injectRenderOptions(options);
...
}
这一拆分的意义在于:解决模块循环依赖并降低渲染调用的注入开销。Host(packages/rax/src/vdom/host.js)是运行时全部可变状态的容器,其结构如下:
export default {
__mountID: 1,
__isUpdating: false,
// Inject
driver: null,
// Roots
rootComponents: {},
rootInstances: {},
// Current owner component
owner: null,
};
组件类注入只需在模块初始化时做一次;而 driver / measurer 属于"每次渲染传入的选项",必须放在 render() 的调用路径中动态注入,否则 driver.createBody()、driver.beforeRender、driver.afterRender(见 packages/rax/src/vdom/instance.js)将拿不到渲染驱动。
driver 缺失时的错误处理
injectRenderOptions 对 driver 做了空值防护。对应生产环境的压缩错误码定义在 packages/rax/src/error.js:
/**
* Minified code:
* 1: Hooks called outside a component, or multiple version of Rax are used.
* 6: Invalid component type, expected a class or function component.
* 4: Too many re-renders, the number of renders is limited to prevent an infinite loop.
* 5: Rax driver not found.
*/
即:开发环境下直接抛出 Rax driver not found.,生产环境(NODE_ENV === 'production')抛出 Error: #5 压缩错误,帮助减小包体积的同时保留可排查的错误码。
二、1.2.2:lib/compat 构建产物路径修复
变更内容
fix:
lib/compatbundle error path
Rax 提供了 React 兼容层入口 src/compat/index.js(packages/rax/src/compat/index.js),它在核心 API 之上补充了 Children、isValidElement、createFactory、cloneElement 等 React 风格 API,并为 Component.prototype 打上 isReactComponent 标记:
import * as RaxCore from 'rax';
import Children from 'rax-children';
import isValidElement from 'rax-is-valid-element';
import createFactory from 'rax-create-factory';
import cloneElement from 'rax-clone-element';
const Rax = RaxCore;
Rax.Children = Children;
Rax.isValidElement = isValidElement;
Rax.createFactory = createFactory;
Rax.cloneElement = cloneElement;
Rax.Component.prototype.isReactComponent = {};
export * from 'rax';
export { Children, isValidElement, createFactory, cloneElement };
export default Rax;
构建配置的证据
该兼容包的独立打包逻辑位于 scripts/dist-core.js 的 build() 调用中:
// Build rax compat react version to rax/lib/compat/index.js
// It needs external ../../index, which won't bundle rax into lib/compat/index.js
// If bundle rax into lib/compat/index.js, it will exist multiple version rax in the project with rax and react are used together
build({
packageName: 'rax',
name: 'Rax',
entry: 'src/compat/index.js',
outputPath: './packages/rax/lib/compat/index.js',
format: CJS,
external: ['rax', 'rax-children', 'rax-is-valid-element', 'rax-create-factory', 'rax-clone-element'],
replaceValues: { 'process.env.RAX_VERSION': raxVersion },
});
源码注释明确说明了这次修复的设计意图:lib/compat/index.js 必须把 rax 等核心依赖声明为 external,不能把 rax 打进兼容包内部。否则当项目同时使用 rax 与 react 时,会存在多个版本的 Rax 实例,导致 Host 状态分裂、ref 无法挂载、hooks 状态错乱等难以排查的问题(对应 error.js 中的压缩错误码 1 "multiple version of Rax are used" 和错误码 3 "Ref can not attach because multiple copies of Rax are used")。
1.2.2 修复的正是该产物输出路径的问题:正确输出到 packages/rax/lib/compat/index.js,而非错误路径,从而保证 import Rax from 'rax/lib/compat' 能稳定加载到兼容层。
三、1.2.1(一):输出格式重构——避免 IIFE 与 CJS 混用
变更内容
refactor: change output result format, avoid mixing
IIFEandCJS
从 scripts/dist-core.js 的 buildCorePackages 可以看出,Rax 核心包现在按六种形态产出构建物:
function buildCorePackages(options) {
build(options); // UMD(开发版)
build({ ...options, shouldMinify: true }); // UMD(压缩版)
build({ ...options, format: CJS }); // CJS(开发版)
build({ ...options, format: CJS, shouldMinify: true }); // CJS(压缩版)
build({ ...options, format: ESM }); // ESM(开发版)
build({ ...options, format: ESM, shouldMinify: true }); // ESM(压缩版)
}
对应文件扩展名规则在 getExtension() 中定义:
function getExtension(format) {
let ext = '.js';
switch (format) {
case 'umd': ext = '.umd.js';
break;
case 'esm': ext = '.mjs';
break;
}
return ext;
}
这次重构要解决的问题
在 Rollup 的 output 配置中(scripts/dist-core.js),exports: 'named' 与 esModule: format === ESM 的设定要求每个产物使用统一的模块格式:
const output = {
name,
exports: 'named',
sourcemap: 'hidden',
compact: false, // This will minify the wrapper code generated by rollup.
freeze: false,
strict: false,
esModule: format === ESM,
};
如果同一份代码中既出现 IIFE 包装((function () { ... })())又出现 CJS 的 module.exports / exports 语句,会导致:
- Node/CommonJS 环境:拿到的是被 IIFE 包裹后未正确导出 API 的 bundle,
require('rax')得到的可能是空对象; - 浏览器直接
<script>引入:UMD 逻辑与 CJS 分支互相干扰,window.Rax可能未挂载。
统一输出格式(UMD 只出 .umd.js、CJS 只出 .js、ESM 只出 .mjs)后,各模块系统的加载路径不再有歧义。构建时还会通过 replace 插件把 process.env.NODE_ENV 与 process.env.RAX_VERSION 替换为真实值:
replace({
values: {
...replaceValues,
'process.env.NODE_ENV': JSON.stringify(shouldMinify ? 'production' : 'development'),
},
preventAssignment: true,
}),
同时 getRaxVersion() 会读取 packages/rax/package.json 中的 version 字段(当前仓库为 1.2.3)注入到 process.env.RAX_VERSION,并在入口 packages/rax/src/index.js 中作为 version 导出。
另外,值得注意 scripts/compile.js 中的 IGNORE_COMPILE_PACKAGES = ['rax']:rax 核心包的 src 不会走 babel 逐文件转译流程,而是由 scripts/dist-core.js 统一打包,这也是输出格式一致性得以保障的前提之一。
四、1.2.1(二):卸载组件上更新不再抛错
变更内容
chore: avoid throw error when update unmounted component
此前,在已卸载(unmounted)组件上调用 setState 会直接抛出异常,容易在异步回调、定时器回调中引发应用崩溃。1.2.1 起改为:静默返回 + 开发环境告警。
源码级实现
该逻辑位于 packages/rax/src/vdom/updater.js 的 requestUpdate():
function requestUpdate(component, partialState, callback) {
let internal = component[INTERNAL];
if (!internal) {
if (process.env.NODE_ENV !== 'production') {
// Block other render
Host.__isUpdating = false;
console.error(
"Warning: Can't perform a Rax state update on an unmounted component. This " +
'is a no-op, but it indicates a memory leak in your application. To ' +
'fix, cancel all subscriptions and asynchronous tasks in %s.',
component.__isReactiveComponent
? 'a useEffect cleanup function'
: 'the componentWillUnmount method',
);
}
return;
}
...
}
关键点:
- 组件卸载后,其
<a href="https://link.gitcode.com/i/7a30bb3bcb0080f5c76e0ab11c377a96" target="_blank">INTERNAL]内部实例会被清空(见 [packages/rax/src/vdom/base.js 的__destoryComponent(),其中将this[INSTANCE]、[INTERNAL]置空),此时internal为 falsy; - 新版逻辑直接
return,不再抛出 Error,更新请求被安全忽略(no-op); - 开发环境通过
console.error输出带有修复建议的告警,且告警文案根据组件类型区分:函数组件提示在useEffect cleanup function中清理,类组件提示在componentWillUnmount方法中清理。
测试用例印证
packages/rax/src/tests/asyncUpdate.js 中有两组测试精确覆盖了这一行为:
类组件场景(should warn about class component):Child.componentDidMount 里 setTimeout 延迟 1 秒调用 setState,但父组件在此之前把 Child 从树上移除。测试断言输出告警:
Warning: Can't perform a Rax state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
函数组件场景(should warn about function component):Child 内 useEffect 中 setTimeout 延迟调用 setName,父组件提前卸载。断言输出:
Warning: Can't perform a Rax state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
工程实践建议
虽然不再抛错,但告警本身就是内存泄漏的信号。正确姿势是:
- 类组件:在
componentWillUnmount中清理定时器、取消订阅(clearTimeout、unsubscribe等); - 函数组件:在
useEffect返回的 cleanup 函数中清理,保证异步任务不会在卸载后触发状态更新。
五、1.2.1(三):getDerivedStateFromError 错误信息修复
变更内容
fix: add error message to
getDerivedStateFromErrorhook
Rax 的沙箱错误处理逻辑位于 packages/rax/src/vdom/performInSandbox.js。其核心是 handleError():当渲染过程抛出异常时,向上寻找最近的错误边界(error boundary):
export function handleError(instance, error) {
let boundary = getNearestParent(instance, parent => {
return parent.componentDidCatch || parent.constructor && parent.constructor.getDerivedStateFromError;
});
if (boundary) {
scheduleLayout(() => {
const boundaryInternal = boundary[INTERNAL];
// Should not attempt to recover an unmounting error boundary
if (boundaryInternal) {
performInSandbox(() => {
if (boundary.componentDidCatch) {
boundary.componentDidCatch(error);
}
// Update state to the next render to show the fallback UI.
if (boundary.constructor && boundary.constructor.getDerivedStateFromError) {
const state = boundary.constructor.getDerivedStateFromError(error);
boundary.setState(state);
}
}, boundaryInternal.__parentInstance);
}
});
} else {
// Do not break when error happens
scheduler(() => {
throw error;
}, 0);
}
}
错误边界组件须实现以下任一(或两个都实现)生命周期方法:
- 静态方法
static getDerivedStateFromError(error):接收捕获到的 error 对象,返回新的 state,用于渲染 fallback UI; - 实例方法
componentDidCatch(error):用于记录错误信息(如上报日志)。
1.2.1 修复前,getDerivedStateFromError 钩子在某些路径下拿不到错误信息;修复后,捕获到的原始 error 对象会被原样传入该钩子,便于在 fallback UI 中展示具体错误内容。
测试用例印证
packages/rax/src/vdom/tests/composite.js 中针对该行为有三组测试:
1. 通过 getDerivedStateFromError 更新 state 渲染 fallback UI(should update state to the next render when catch error.):
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// log
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
function BrokenRender(props) {
throw new Error('Hello');
}
2. 仅凭 getDerivedStateFromError 即可捕获错误(should catch error only with getDerivedStateFromError.):不实现 componentDidCatch 也能完成错误捕获与 fallback 渲染。
3. 捕获到的是原始错误对象(should catch the exact error with getDerivedStateFromError.):
let exampleError = new Error('Example error message');
// ...
static getDerivedStateFromError(error) {
caughtError = error;
return { hasError: true, error };
}
// ...
expect(caughtError).toBe(exampleError);
expect(container.childNodes[0].childNodes[0].data).toBe('Example error message');
该测试明确断言:getDerivedStateFromError 收到的 error 参数与渲染时抛出的 exampleError 是同一个对象,并且 fallback UI 能展示 error.message —— 这正是 1.2.1 "add error message to getDerivedStateFromError hook" 所保证的能力。
边界情形
handleError 中还处理了一个重要边界:正在卸载中的错误边界不再尝试恢复(// Should not attempt to recover an unmounting error boundary),因为此时 boundary[INTERNAL] 已被清空,scheduleLayout 中的回调会安全跳过。对应测试 should not attempt to recover an unmounting error boundary(见 packages/rax/src/vdom/tests/composite.js):父组件先卸载、子组件卸载过程中抛错,此时不会触发错误的边界恢复逻辑。
六、版本脉络与演进小结
| 版本 | 变更 | 核心源码位置 | 意义 |
|---|---|---|---|
| 1.2.3 | inject 与 injectRenderOptions 职责拆分 |
packages/rax/src/vdom/inject.js、packages/rax/src/vdom/injectRenderOptions.js、packages/rax/src/render.js | 缓解模块循环依赖,渲染选项在 render 调用路径上动态注入 |
| 1.2.2 | lib/compat bundle 路径修复 |
scripts/dist-core.js、packages/rax/src/compat/index.js | 保证兼容包稳定输出、避免多实例 Rax |
| 1.2.1 | 输出格式统一(避免 IIFE 与 CJS 混用) | scripts/dist-core.js | 规范 UMD/CJS/ESM 产物,消除模块加载歧义 |
| 1.2.1 | 卸载组件更新不再抛错 | packages/rax/src/vdom/updater.js、packages/rax/src/tests/asyncUpdate.js | 异步更新卸载组件变为安全 no-op + 开发告警 |
| 1.2.1 | getDerivedStateFromError 错误信息修复 |
packages/rax/src/vdom/performInSandbox.js、packages/rax/src/vdom/tests/composite.js | 错误边界能拿到原始 error 对象并展示具体信息 |
这三轮演进体现了 Rax 核心引擎在工程健壮性(卸载安全、错误边界信息完整)与构建规范化(注入职责清晰、产物格式统一)两个方向上的持续打磨。对于使用 Rax 的开发者而言:
- 升级到 1.2.1+ 后,应把"异步回调中可能对已卸载组件 setState"的代码视为告警级问题而非崩溃级问题,但仍需主动清理以消除内存泄漏;
- 错误边界可以放心依赖
getDerivedStateFromError的error参数展示具体错误内容; - 若以
rax/lib/compat方式使用 React 兼容 API,需确保构建产物来自正确的lib/compat路径,避免多实例 Rax 带来的状态分裂。