AWS Lambda中flat-cache的load方法报错:this.create is not a function
AWS Lambda中flat-cache的load方法报错
this.create is not a function的原因分析 问题背景
原本长期正常运行的AWS Lambda代码突然报错:this.create is not a function,报错位置指向flat-cache库中load方法调用this.create的行。将代码中的loadCache(即load方法)替换为create方法后,功能恢复正常。本地测试模拟相同逻辑并未出现该问题,仅在Lambda环境中触发错误。
相关代码片段
用户的CacheStore实现
import { load as loadCache, Cache } from 'flat-cache'; ... export class CacheStore { cache: Cache; constructor() { if(process.env.stageName != 'Dev'){ this.cache = loadCache(CACHE_ID, '/cache'); } else { this.cache = loadCache(CACHE_ID); } } ...
flat-cache库中load与create方法的实现
module.exports = { /** * Alias for create. Should be considered depreacted. Will be removed in next releases * * @method load * @param docId {String} the id of the cache, would also be used as the name of the file cache * @param [cacheDir] {String} directory for the cache entry * @returns {cache} cache instance */ load: function (docId, cacheDir) { return this.create(docId, cacheDir); // <- 报错行 }, /** * Load a cache identified by the given Id. If the element does not exists, then initialize an empty * cache storage. * * @method create * @param docId {String} the id of the cache, would also be used as the name of the file cache * @param [cacheDir] {String} directory for the cache entry * @returns {cache} cache instance */ create: function (docId, cacheDir) { var obj = Object.create(cache); obj.load(docId, cacheDir); return obj; }, }
本地测试代码(运行正常)
(() => { console.log('starting') })(); module.exports = { load: function (name) { return this.create(name) }, create: function(name) { console.log(name); return name + ' yelled' } }
问题原因分析
核心问题出在函数调用时的this绑定差异:
- 本地测试中,通常是通过CommonJS的
require方式加载模块,然后以obj.load()的形式调用方法——此时load作为导出对象的属性被调用,this会绑定到该导出对象,因此能正常访问this.create。 - 在Lambda环境中,你使用ES模块的
import语法单独提取了load函数(import { load as loadCache } from 'flat-cache'),这相当于把load函数从原对象中剥离出来成为独立函数。Lambda的Node.js运行环境默认启用严格模式,此时独立调用该函数时,this会指向undefined,自然找不到this.create方法。
而create方法能正常运行,是因为它内部没有依赖原导出对象的this——它通过Object.create(cache)创建实例,调用的是实例自身的load方法,而非原对象的方法,所以不受this绑定变化的影响。
另外,flat-cache的文档已明确标注load是废弃的别名,改用create本身就是官方推荐的正确做法,本地环境的调用方式只是恰好掩盖了this绑定的潜在问题。
内容的提问来源于stack exchange,提问作者Bishonen_PL
相关产品推荐
相关产品推荐

