TypeError:this.activateMode不是函数Gutenberg WordPress

问题描述

我在自己的自定义Gutenberg插件中遇到了问题。有时,这会导致Gutenberg编辑器因以下错误消息而中断。

ypeError: this.activateMode is not a function

react-dom.min.js?ver=16.9.0:103 TypeError: this.activateMode is not a function
    at media-views.min.js?ver=5.5:2
    at st (build.js?ver=1.0.0:9)
    at Function.sa (build.js?ver=1.0.0:9)
    at i._createModes (media-views.min.js?ver=5.5:2)
    at initialize (media-views.min.js?ver=5.5:2)
    at initialize (media-views.min.js?ver=5.5:2)
    at initialize (media-views.min.js?ver=5.5:2)
    at i.h.View (backbone.min.js?ver=1.4.0:2)
    at i.constructor (wp-backbone.min.js?ver=5.5:2)
    at i.constructor (media-views.min.js?ver=5.5:2)

我还关注了以下文章https://wpdevelopment.courses/articles/how-to-fix-activatemode-is-not-a-function-error-in-gutenberg/

根据上面的文章,该问题某种程度上是由Lodash依赖性引起的。因此,我删除了Lodash。但是似乎没有什么可以解决错误

仍然,问题仍然存在。并非总是如此,但是偶尔。

注意:当用户清除localStorage时,该错误可以暂时消除。

解决此问题方面,我们将不胜感激。

P.S。问题出在这插件上。 https://wordpress.org/plugins/editorplus/

TIA, 穆尼尔

解决方法

这是下划线和lodash库之间的冲突。在媒体库的WordPress中使用下划线,在古腾堡的lodash中使用下划线。问题的tl; dr是因为两个库都使用_的简写,一个包含activateMode函数,而另一个不包含,因此在调用_.activateMode时不存在并且错误被触发。更为复杂的是,这似乎仅是在使用利用了媒体库的组件时真正的问题。

我已经看到了两种解决方案:

  1. 在构建过程中使用@wordpress/scripts软件包。在这里似乎不是问题。
  2. 使用以下帮助器:

/**
 * Determines if _ is lodash or not
 */
export const isLodash = () => {
    let isLodash = false;

    // If _ is defined and the function _.forEach exists then we know underscore OR lodash are in place
    if ( 'undefined' != typeof( _ ) && 'function' == typeof( _.forEach ) ) {

        // A small sample of some of the functions that exist in lodash but not underscore
        const funcs = [ 'get','set','at','cloneDeep' ];

        // Simplest if assume exists to start
        isLodash  = true;

        funcs.forEach( function ( func ) {
            // If just one of the functions do not exist,then not lodash
            isLodash = ( 'function' != typeof( _[ func ] ) ) ? false : isLodash;
        } );
    }

    if ( isLodash ) {
        // We know that lodash is loaded in the _ variable
        return true;
    } else {
        // We know that lodash is NOT loaded
        return false;
    }
};

这样称呼:

/**
 * Address conflicts
 */
if ( isLodash() ) {
    _.noConflict();
}