Like the guy said, it will happen since it is part of the game. But there should be warning signs that the guy has something big and prevent you from losing too many chips.
For example, are you going for 3 streets of value? If I were the pre flop raiser and OOP and he just smooth calls my preflop bet, my flop bet, and turn bet, I would at least check on the river just to be cautious. Even if I did have 2 pairs, 2 streets of value is enough ,because thats the most you could probably ever get if enemy indeed does have something which your 2 pairs beats.
If I were the pre flop raiser and in position and he smooth calls from the blinds, I would still check back one street which at that point, would give him a chance to bet out which is information to me that he may indeed have something like a set in your case.
Just that information alone you gain by checking back one street should help you avoid spots where you're just spewing your chips even though you're already beat.