Adding acid to legumes cooked with baking soda neutralizes the alkaline environment, releasing carbon dioxide gas which, combined with saponins in the legumes, causes excessive foaming.
Legumes contain compounds called saponins, which act like soap and create foam when agitated in water. Baking soda (sodium bicarbonate) is often added to legumes during cooking to soften them by breaking down pectin and hemicellulose in their cell walls. This creates an alkaline environment. When an acid, such as vinegar or lemon juice, is added to this mixture, it reacts with the baking soda. This reaction neutralizes the alkalinity and produces carbon dioxide (CO2) gas. The CO2 gas gets trapped within the saponin-rich liquid, creating a large amount of foam. The saponins stabilize the bubbles, preventing them from easily popping, leading to the excessive foaming you observe. The alkaline environment created by the baking soda also enhances the solubility and foaming properties of the saponins.
To prevent excessive foaming, either avoid adding acid to legumes cooked with baking soda, or rinse the legumes thoroughly after cooking with baking soda to remove residual saponins and baking soda before adding any acidic ingredients.