You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用React-Markdown渲染LaTeX时出现KaTeX解析错误

解决React-Markdown渲染LaTeX的KaTeX解析错误

问题根源

你碰到的Unexpected end of input in a macro argument错误,核心原因有两个:

  1. 插件逻辑冲突:同时启用remarkMath插件和自定义的LaTeX标记替换代码,两者对公式的处理规则相互干扰,导致KaTeX解析时出现语法不完整的情况。
  2. 非标准空格干扰:原始LaTeX内容里的非断空格( )破坏了KaTeX的语法识别,使得解析器找不到闭合的}。

修正方案

方案1:保留自定义标记,移除冲突插件

保留你的_latex$$/$$latex_标记规则,移除remarkMath插件,同时清理公式内的异常空格,确保KaTeX能正确解析:

<Markdown
  key={index}
  remarkPlugins={[remarkGfm]}
  rehypePlugins={[rehypeRaw, rehypeKatex]}
>
  {String.raw`  _latex$$  {}^{\\mathrm{*}} $$latex_ <!-- tag: 401 -->  The materials should not sorb, react, or interfere with the specimen being tested. <!-- tag: 402 --> _latex$$  { }^{\\mathrm{*}}{ }^{2} $$latex_`
    .replace(
      /_latex\$\$(.*?)\$\$latex_/gs,
      (_, mathContent) => {
        // 清理非标准空格和冗余空白,规范LaTeX语法
        const cleanedMath = mathContent.replace(/\s+/g, ' ').trim();
        // 用KaTeX识别的行内公式标记包裹
        return `$${cleanedMath}$`;
      }
    )
    .replace(/(&lt;br\s*\/?&gt;\s*){2,}/g, "<br>")
  }
</Markdown>

方案2:改用插件原生识别,简化标记

如果可以调整LaTeX标记格式,直接用$...$包裹公式,让remarkMath自动处理,无需自定义替换逻辑:

<Markdown
  key={index}
  remarkPlugins={[remarkGfm, remarkMath]}
  rehypePlugins={[rehypeKatex]}
>
  {String.raw`  ${'$'}{}^{\\mathrm{*}}${'$'} <!-- tag: 401 -->  The materials should not sorb, react, or interfere with the specimen being tested. <!-- tag: 402 --> ${'$'}{}^{\\mathrm{*}}{}^{2}${'$'}`
    .replace(/(&lt;br\s*\/?&gt;\s*){2,}/g, "<br>")
  }
</Markdown>

核心注意事项

  • 不要同时使用remarkMath和自定义公式替换逻辑,二者选其一即可。
  • 确保LaTeX内容里没有非标准空格、未闭合的括号或转义错误,这些都会触发KaTeX的解析报错。

内容的提问来源于stack exchange,提问作者Niresh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 11:45:07