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

TinyMCE自定义编辑器模式注册报错求助:TypeError: s.activate is not a function

解决TinyMCE自定义模式激活报错:TypeError: s.activate is not a function

问题分析

报错核心原因是自定义模式的实现不符合TinyMCE的内部要求,大概率是类方法的上下文丢失或注册时机/方式错误,导致TinyMCE无法正确识别并调用activate方法。

解决方案

方案1:改用对象字面量定义模式(推荐)

避开类的上下文绑定问题,直接用对象字面量实现模式逻辑,更贴合TinyMCE的预期:

setup: (editor) => {
  // 注册自定义只读模式,保留搜索功能
  editor.mode.register('testMode', {
    activate: () => {
      console.log('testMode activated');
      // 锁定内容为只读状态
      editor.setReadOnly(true);
      // 启用搜索工具栏按钮
      const searchBtn = editor.ui.registry.getToolbarButton('search');
      if (searchBtn) {
        editor.ui.registry.setToolbarButtonDisabled('search', false);
      }
      // 禁用其他不需要的工具栏按钮
      editor.ui.registry.getAll().toolbarButtons.forEach(btn => {
        if (btn.name !== 'search') {
          editor.ui.registry.setToolbarButtonDisabled(btn.name, true);
        }
      });
    },
    deactivate: () => {
      console.log('testMode deactivated');
      // 恢复内容可编辑
      editor.setReadOnly(false);
      // 恢复所有工具栏按钮的可用状态
      editor.ui.registry.getAll().toolbarButtons.forEach(btn => {
        editor.ui.registry.setToolbarButtonDisabled(btn.name, false);
      });
    },
    editorReadOnly: true
  });
}

方案2:修正类实现的上下文绑定

如果坚持用类结构实现,需要手动绑定方法的上下文,并确保编辑器实例被正确传入:

class TestMode {
  private editor: any;

  constructor(editor: any) {
    this.editor = editor;
    // 绑定方法上下文,避免TinyMCE调用时丢失this指向
    this.activate = this.activate.bind(this);
    this.deactivate = this.deactivate.bind(this);
  }

  activate(): void {
    console.log('testMode activated');
    this.editor.setReadOnly(true);
    // 启用搜索按钮
    const searchBtn = this.editor.ui.registry.getToolbarButton('search');
    if (searchBtn) {
      this.editor.ui.registry.setToolbarButtonDisabled('search', false);
    }
  }

  deactivate(): void {
    console.log('testMode deactivated');
    this.editor.setReadOnly(false);
    // 恢复所有工具栏按钮状态
    this.editor.ui.registry.getAll().toolbarButtons.forEach((btn: any) => {
      this.editor.ui.registry.setToolbarButtonDisabled(btn.name, false);
    });
  }

  // 通过getter确保editorReadOnly属性可被TinyMCE正确读取
  get editorReadOnly(): boolean {
    return true;
  }
}

// 注册时传入当前编辑器实例
setup: (editor) => {
  editor.mode.register('testMode', new TestMode(editor));
}

额外注意事项

  1. 移除setup的async修饰符:除非必须执行异步初始化操作,否则同步注册模式即可,避免注册延迟导致激活时模式未被识别。
  2. 验证激活代码:确保this.tinyMce.editor指向正确的TinyMCE编辑器实例:
if (this.tinyMce?.editor) {
  this.tinyMce.editor.mode.set('testMode');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 18:46:07